【问题标题】:Rename root node of XML (with namespace prefix) in Java在 Java 中重命名 XML 的根节点(带有命名空间前缀)
【发布时间】:2011-11-12 08:52:48
【问题描述】:

我正在尝试使用 org.w3c.dom.Document 类的 renameNode() 方法来重命名 XML 文档的根节点。

我的代码是这样的:

xml.renameNode(Element, "http://newnamespaceURI", "NewRootNodeName");

代码确实重命名了根元素,但没有应用命名空间前缀。硬编码命名空间前缀是行不通的,因为它必须是动态的。

任何想法为什么它不起作用?

非常感谢

【问题讨论】:

    标签: java xml xml-parsing


    【解决方案1】:

    我用 JDK 6 试过了:

    public static void main(String[] args) throws Exception {
      // Create an empty XML document
      Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    
      // Create the root node with a namespace
      Element root = xml.createElementNS("http://oldns", "doc-root");
      xml.appendChild(root);
    
      // Add two child nodes. One with the root namespace and one with another ns    
      root.appendChild(xml.createElementNS("http://oldns", "child-node-1"));
      root.appendChild(xml.createElementNS("http://other-ns", "child-node-2"));
    
      // Serialize the document
      System.out.println(serializeXml(xml));
    
      // Rename the root node
      xml.renameNode(root, "http://new-ns", "new-root");
    
      // Serialize the document
      System.out.println(serializeXml(xml));
    }
    
    /*
     * Helper function to serialize a XML document.
     */
    private static String serializeXml(Document doc) throws Exception {
      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      Source source = new DOMSource(doc.getDocumentElement());
      StringWriter out = new StringWriter();
      Result result = new StreamResult(out);
      transformer.transform(source, result);
      return out.toString();
    }
    

    输出是(我添加的格式):

    <doc-root xmlns="http://oldns">
      <child-node-1/>
      <child-node-2 xmlns="http://other-ns"/>
    </doc-root>
    
    <new-root xmlns="http://new-ns">
      <child-node-1 xmlns="http://oldns"/>
      <child-node-2 xmlns="http://other-ns"/>
    </new-root>
    

    所以它按预期工作。根节点有一个新的本地名称和新的命名空间,而子节点保持不变,包括它们的命名空间。

    【讨论】:

    • 它也为我做,但它不应用命名空间前缀,例如在您的示例中,带有前缀的 new-root 看起来像这样
    【解决方案2】:

    我设法通过查找命名空间前缀来对它进行排序,如下所示:

    String namespacePrefix = rootelement.lookupPrefix("http://newnamespaceURI");
    

    然后将其与 renameNode 方法一起使用:

    xml.renameNode(Element, "http://newnamespaceURI", namespacePrefix + ":" + "NewRootNodeName");
    

    【讨论】:

      猜你喜欢
      • 2015-04-14
      • 2015-06-05
      • 1970-01-01
      • 1970-01-01
      • 2023-02-18
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      相关资源
      最近更新 更多