Changing node name of xml-node with Java

后端 未结 5 1541
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 05:42

I have following scenario: I have a XML-Document, e.g. like this



    

        
相关标签:
5条回答
  • 2020-12-30 06:04

    Your tag1 is invalid. It doesn't have closing >. Also the attributes should be quoted. It should look like this,

    <someRootElement>
    <tag1>
        <tag2 
            someKey="someValue"
            someKey2="someValue2"
        />
        <tag3/>
        <tag4
            newKey="newValue"
            newKey2="newValue2"
        />
    </tag1>
    </someRootElement>
    

    Try with the corrected XML. It should work.

    0 讨论(0)
  • 2020-12-30 06:11

    Using Document.renameNode:

    NodeList nodes = document.getElementsByTagName("tag1");
    for (Node eachNode: nodes) {
      document.renameNode(eachNode, null, "reallyCoolTag");
    }
    
    0 讨论(0)
  • 2020-12-30 06:17

    You could use an XSL Transformation (XSLT) for this:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      version="1.0">
      <xsl:output method="xml" indent="yes" />
      <xsl:template match="*"> <!-- match anything -->
        <xsl:copy>
          <xsl:copy-of select="@*" />
          <xsl:apply-templates />
        </xsl:copy>
      </xsl:template>
      <xsl:template match="tag1"> <!-- switch the element name -->
        <xsl:element name="reallyCoolTag">
          <xsl:copy-of select="@*" />
          <xsl:apply-templates />
        </xsl:element>
      </xsl:template>
    </xsl:stylesheet>
    

    This can be used with the javax.xml.transform package (Java 1.4 and above):

    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = transFactory.newTransformer(new StreamSource(
        new File("RenameTag.xslt")));
    transformer
        .transform(new DOMSource(document), new StreamResult(System.out));
    

    See DOMResult if you want a Document as the output.

    0 讨论(0)
  • 2020-12-30 06:22

    Just call setName("reallyCoolTag") on the element(s) you want to rename. There is no need to copy the children around; the name attribute of an element is a mutable field.

    0 讨论(0)
  • 2020-12-30 06:24

    As you did get the attributes:

    NamedNodeMap nnm = nodes.item(i).getAttributes();
    

    and you added these attributes to the new element,

    You should get the children of nodes.item(i) and set them in the new node.

    You can use for ex.:

    neu.addContent(nodes.item(i).getChildren());
    
    0 讨论(0)
提交回复
热议问题