19

既に作成されたDocument オブジェクトを扱っています。そのベース名前空間 (属性名「xmlns」) を特定の値に設定できる必要があります。私の入力はDOMで、次のようなものです:

<root>...some content...</root>

私が必要としているのは、次のような DOM です。

<root xmlns="myNamespace">...some content...</root>

それでおしまい。簡単ですね。違う!DOMではありません!

私は次のことを試しました:

1) doc.getDocumentElement().setAttribute("xmlns","myNamespace") の使用

空の xmlns を持つドキュメントを取得します (他の属性名でも機能します! )

<root xmlns="">...</root>

2) renameNode(...) の使用

最初にドキュメントを複製します。

Document input = /*that external Document whose namespace I want to alter*/;

DocumentBuilderFactory BUILDER_FACTORY_NS = DocumentBuilderFactory.newInstance();
BUILDER_FACTORY_NS.setNamespaceAware(true);
Document output = BUILDER_NS.newDocument();
output.appendChild(output.importNode(input.getDocumentElement(), true));

本当に document.clone() がありませんが、おそらくそれは私だけです。

ルート ノードの名前を変更します。

output.renameNode(output.getDocumentElement(),"myNamespace",
    output.getDocumentElement().getTagName());

今、それは簡単ではありませんか?;)

私が今得たものは次のとおりです。

<root xmlns="myNamespace">
    <someElement xmlns=""/>
    <someOtherElement xmlns=""/>
</root>

したがって(私たち全員が予想したとおりですよね?) 、これにより、ルート ノードの名前空間のみが名前変更されます。

のろい、ドム!

これを再帰的に行う方法はありますか (独自の再帰メソッドを記述せずに)?

助けてください ;)

DOM を別のものに変換し、そこで名前空間を変更して元に戻すなど、手の込んだ回避策を実行するようにアドバイスしないでください。XML を操作するための最速の標準的な方法であるため、DOM が必要です。

注: 最新の JDK を使用しています。

編集名前空間プレフィックス
に関係する質問から間違った仮定を削除しました。

4

8 に答える 8

11

今日も同じ問題がありました。@ivan_ivanovich_ivanoffの回答の一部を使用することになりましたが、再帰を削除し、いくつかのバグを修正しました。

非常に重要です。古い名前空間の場合null、2つの翻訳を追加する必要があります。1つはからnull新しいへnamespaceURI、もう1つはから""新しいへnamespaceURIです。これは、toを最初に呼び出すと、 torenameNodeを持つ既存のノードが変更されるために発生します。null namespaceURIxmlns=""

使用例:

Document xmlDoc = ...;

new XmlNamespaceTranslator()
    .addTranslation(null, "new_ns")
    .addTranslation("", "new_ns")
    .translateNamespaces(xmlDoc);

// xmlDoc will have nodes with namespace null or "" changed to "new_ns"

完全なソースコードは次のとおりです。

public  class XmlNamespaceTranslator {

    private Map<Key<String>, Value<String>> translations = new HashMap<Key<String>, Value<String>>();

    public XmlNamespaceTranslator addTranslation(String fromNamespaceURI, String toNamespaceURI) {
        Key<String> key = new Key<String>(fromNamespaceURI);
        Value<String> value = new Value<String>(toNamespaceURI);

        this.translations.put(key, value);

        return this;
    }

    public void translateNamespaces(Document xmlDoc) {
        Stack<Node> nodes = new Stack<Node>();
        nodes.push(xmlDoc.getDocumentElement());

        while (!nodes.isEmpty()) {
            Node node = nodes.pop();
            switch (node.getNodeType()) {
            case Node.ATTRIBUTE_NODE:
            case Node.ELEMENT_NODE:
                Value<String> value = this.translations.get(new Key<String>(node.getNamespaceURI()));
                if (value != null) {
                    // the reassignment to node is very important. as per javadoc renameNode will
                    // try to modify node (first parameter) in place. If that is not possible it
                    // will replace that node for a new created one and return it to the caller.
                    // if we did not reassign node we will get no childs in the loop below.
                    node = xmlDoc.renameNode(node, value.getValue(), node.getNodeName());
                }
                break;
            }

            // for attributes of this node
            NamedNodeMap attributes = node.getAttributes();
            if (!(attributes == null || attributes.getLength() == 0)) {
                for (int i = 0, count = attributes.getLength(); i < count; ++i) {
                    Node attribute = attributes.item(i);
                    if (attribute != null) {
                        nodes.push(attribute);
                    }
                }
            }

            // for child nodes of this node
            NodeList childNodes = node.getChildNodes();
            if (!(childNodes == null || childNodes.getLength() == 0)) {
                for (int i = 0, count = childNodes.getLength(); i < count; ++i) {
                    Node childNode = childNodes.item(i);
                    if (childNode != null) {
                        nodes.push(childNode);
                    }
                }
            }
        }
    }

    // these will allow null values to be stored on a map so that we can distinguish
    // from values being on the map or not. map implementation returns null if the there
    // is no map element with a given key. If the value is null there is no way to
    // distinguish from value not being on the map or value being null. these classes
    // remove ambiguity.
    private static class Holder<T> {

        protected final T value;

        public Holder(T value) {
            this.value = value;
        }

        public T getValue() {
            return value;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((value == null) ? 0 : value.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Holder<?> other = (Holder<?>) obj;
            if (value == null) {
                if (other.value != null)
                    return false;
            } else if (!value.equals(other.value))
                return false;
            return true;
        }

    }

    private static class Key<T> extends Holder<T> {

        public Key(T value) {
            super(value);
        }

    }

    private static class Value<T> extends Holder<T> {

        public Value(T value) {
            super(value);
        }

    }
}
于 2010-10-01T14:29:32.160 に答える
8

プレフィックスを設定するだけでなく、名前空間をどこかで宣言する必要があります。

[編集] パッケージを調べるorg.w3c.domと、名前空間 URI を使用して Document ノードを作成できることを除いて、名前空間がまったくサポートされていないことがわかります。

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
DOMImplementation DOMImplementation = builder.getDOMImplementation();
Document doc = DOMImplementation.createDocument(
    "http://www.somecompany.com/2005/xyz", // namespace
    "root",
    null /*DocumentType*/);

Element root = doc.getDocumentElement();
root.setPrefix("xyz");
root.setAttribute(
    "xmlns:xyz",
    "http://www.somecompany.com/2005/xyz");

Java 5 (およびそれ以降) の標準 W3C DOM API では、ノードの名前空間を変更することはできません。

しかし、W3C DOM API はほんの 2 つのインターフェイスにすぎません。したがって、実装 (つまり、ドキュメント インスタンスの実際のクラス) を調べて、それを実際の型にキャストする必要があります。この型には追加のメソッドが必要です。運が良ければ、それらを使用して名前空間を変更できます。

于 2009-09-29T13:16:54.053 に答える
5

さて、ここに再帰的な「解決策」があります:(
誰かがこれを行うためのより良い方法を見つけてくれることを願っています)

public static void renameNamespaceRecursive(Document doc, Node node,
        String namespace) {

    if (node.getNodeType() == Node.ELEMENT_NODE) {
        System.out.println("renaming type: " + node.getClass()
            + ", name: " + node.getNodeName());
        doc.renameNode(node, namespace, node.getNodeName());
    }

    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); ++i) {
        renameNamespaceRecursive(doc, list.item(i), namespace);
    }
}

ノードタイプ ELEMENT_NODE のみの名前を変更するのが正しいかどうか、または他のノードタイプの名前を変更する必要があるかどうかはわかりませんが、うまくいくようです。

于 2009-09-29T14:21:58.533 に答える
1

saxパーサーを使用してxml名前空間を変更できます。これを試してください

import java.util.ListIterator;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;
import org.dom4j.Visitor;
import org.dom4j.VisitorSupport;
import org.dom4j.io.SAXReader;

public class VisitorExample {

  public static void main(String[] args) throws Exception {
    Document doc = new SAXReader().read("test.xml");
    Namespace oldNs = Namespace.get("oldNamespace");
    Namespace newNs = Namespace.get("newPrefix", "newNamespace");
    Visitor visitor = new NamespaceChangingVisitor(oldNs, newNs);
    doc.accept(visitor);
    System.out.println(doc.asXML());
  }
}

class NamespaceChangingVisitor extends VisitorSupport {
  private Namespace from;
  private Namespace to;

  public NamespaceChangingVisitor(Namespace from, Namespace to) {
    this.from = from;
    this.to = to;
  }

  public void visit(Element node) {
    Namespace ns = node.getNamespace();

    if (ns.getURI().equals(from.getURI())) {
      QName newQName = new QName(node.getName(), to);
      node.setQName(newQName);
    }

    ListIterator namespaces = node.additionalNamespaces().listIterator();
    while (namespaces.hasNext()) {
      Namespace additionalNamespace = (Namespace) namespaces.next();
      if (additionalNamespace.getURI().equals(from.getURI())) {
        namespaces.remove();
      }
    }
  }

}
于 2011-04-14T08:26:39.663 に答える
1

ドキュメント ノードに属性を設定するという、Ivan の元の投稿のわずかなバリエーションが役に立ちました。

xslRoot.setAttribute("xmlns:fo", "http://www.w3.org/1999/XSL/Format");

どこ

  • xslRootはドキュメント/ルート要素/ノードです。
  • foは名前空間 ID です

それが誰かを助けることを願っています!

マイク・ワッツ

于 2012-11-06T11:00:33.717 に答える
0

Xerces クラスの使用に問題がなければ、属性と要素の URI を修正した URI に置き換える DOMParser を作成できます。

import org.apache.xerces.parsers.DOMParser;

public static class MyDOMParser extends DOMParser {
    private Map<String, String> fixupMap = ...;

    @Override
    protected Attr createAttrNode(QName attrQName)
    {
        if (fixupMap.containsKey(attrQName.uri))
            attrQName.uri = fixupMap.get(attrQName.uri);
        return super.createAttrNode(attrQName);
    }

    @Override
    protected Element createElementNode(QName qName)
    {
        if (fixupMap.containsKey(qName.uri))
            qName.uri = fixupMap.get(qName.uri);
        return super.createElementNode(qName);
    }       
}

他の場所では、解析できます

DOMParse p = new MyDOMParser(...);
p.parse(new InputSource(inputStream));
Document doc = p.getDocument();
于 2013-02-13T19:50:40.233 に答える
-1

org.jdom.Element を使用して解決しました:

ジャワ:

import org.jdom.Element;
...
Element kml = new Element("kml", "http://www.opengis.net/kml/2.2");

XML:

<kml xmlns="http://www.opengis.net/kml/2.2">; 
...
</kml>
于 2013-07-11T08:27:31.683 に答える