Java:如何用包装所有元素在 org.w3c.dom 中?

发布于 2024-10-25 09:27:18 字数 528 浏览 2 评论 0原文

我的目标是用标签

public static void main(String[] args){
    org.w3c.dom.DOMDocument doc;
    paintAllNodes(doc, 0);
}

public static void paintAllNodes(Node node, int level) {
    // Process node

    // If there are any children, visit each one
    NodeList list = node.getChildNodes();
    for (int i=0; i<list.getLength(); i++) {
        // Get child node
        Node childNode = list.item(i);        

        // Visit child node
        paintAllNodes(childNode, level+1);
    }
}

My goal is to wrap every single dom elements (Node.ELEMENT_NODE) on current org.w3c.dom.Document with tag <something style="background-color:red"></something>.

public static void main(String[] args){
    org.w3c.dom.DOMDocument doc;
    paintAllNodes(doc, 0);
}

public static void paintAllNodes(Node node, int level) {
    // Process node

    // If there are any children, visit each one
    NodeList list = node.getChildNodes();
    for (int i=0; i<list.getLength(); i++) {
        // Get child node
        Node childNode = list.item(i);        

        // Visit child node
        paintAllNodes(childNode, level+1);
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

睫毛上残留的泪 2024-11-01 09:27:18

解决此类问题(对于任何 XML 转换)最简单的方法之一是使用 XSLT

此 XSLT 转换

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="*">
 <something style="background-color:red">
   <xsl:copy>
    <xsl:copy-of select="@*"/>
    <xsl:apply-templates select="node()"/>
   </xsl:copy>
  </something>
 </xsl:template>
</xsl:stylesheet>

当应用于任何 XML 文档时,例如这个:

<nums>
  <num>01</num>
  <num>02</num>
  <num>03</num>
  <num>04</num>
  <num>05</num>
  <num>06</num>
  <num>07</num>
  <num>08</num>
  <num>09</num>
  <num>10</num>
</nums>

产生所需的正确结果

<something style="background-color:red">
   <nums>
      <something style="background-color:red">
         <num>01</num>
      </something>
      <something style="background-color:red">
         <num>02</num>
      </something>
      <something style="background-color:red">
         <num>03</num>
      </something>
      <something style="background-color:red">
         <num>04</num>
      </something>
      <something style="background-color:red">
         <num>05</num>
      </something>
      <something style="background-color:red">
         <num>06</num>
      </something>
      <something style="background-color:red">
         <num>07</num>
      </something>
      <something style="background-color:red">
         <num>08</num>
      </something>
      <something style="background-color:red">
         <num>09</num>
      </something>
      <something style="background-color:red">
         <num>10</num>
      </something>
   </nums>
</something>

注意:留给读者练习如何在 Java 代码中启动 XSLT 转换:)

One of the simplest ways to solve such kind of problems (as for any XML transformation) is by using XSLT.

This XSLT transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="*">
 <something style="background-color:red">
   <xsl:copy>
    <xsl:copy-of select="@*"/>
    <xsl:apply-templates select="node()"/>
   </xsl:copy>
  </something>
 </xsl:template>
</xsl:stylesheet>

when applied on any XML document, for example this one:

<nums>
  <num>01</num>
  <num>02</num>
  <num>03</num>
  <num>04</num>
  <num>05</num>
  <num>06</num>
  <num>07</num>
  <num>08</num>
  <num>09</num>
  <num>10</num>
</nums>

produces the wanted, correct result:

<something style="background-color:red">
   <nums>
      <something style="background-color:red">
         <num>01</num>
      </something>
      <something style="background-color:red">
         <num>02</num>
      </something>
      <something style="background-color:red">
         <num>03</num>
      </something>
      <something style="background-color:red">
         <num>04</num>
      </something>
      <something style="background-color:red">
         <num>05</num>
      </something>
      <something style="background-color:red">
         <num>06</num>
      </something>
      <something style="background-color:red">
         <num>07</num>
      </something>
      <something style="background-color:red">
         <num>08</num>
      </something>
      <something style="background-color:red">
         <num>09</num>
      </something>
      <something style="background-color:red">
         <num>10</num>
      </something>
   </nums>
</something>

Note: It is left as an exercise to the reader how to initiate an XSLT transformation in Java code :)

柠檬色的秋千 2024-11-01 09:27:18

这会将每个 Node.ELEMENT_NODE 包装在 org.w3c.dom.Document 中,并带有 标记:

public static void paintAllNodes(Document doc) {
    // build list of Node.ELEMENT_NODE to process
    List<Node> nodes = new ArrayList<Node>();
    NodeList list = doc.getElementsByTagName("*");
    for (int i = 0; i < list.getLength(); i++) {
        Node node = list.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            nodes.add(node);
        }
    }

    // iterate through each node and wrap with <something> tag
    for (Node node : nodes) {
        // remember the next sibling for inserting at end
        Node nextSibling = node.getNextSibling();

        // remember the parent and remove this node from it
        Node parent = node.getParentNode();
        parent.removeChild(node);

        // create <something> element and attach node
        Element element = doc.createElement("something");
        NamedNodeMap attributes = element.getAttributes();
        Attr attr = doc.createAttribute("style");
        attr.setNodeValue("background-color:red");
        attributes.setNamedItem(attr);
        element.appendChild(node);

        // insert new element where the node was 
        parent.insertBefore(element, nextSibling);
    }
}

如果您想排除然后在第一个 for 循环中将所有节点过滤掉。

This will wrap every Node.ELEMENT_NODE in a org.w3c.dom.Document with a <something> tag:

public static void paintAllNodes(Document doc) {
    // build list of Node.ELEMENT_NODE to process
    List<Node> nodes = new ArrayList<Node>();
    NodeList list = doc.getElementsByTagName("*");
    for (int i = 0; i < list.getLength(); i++) {
        Node node = list.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            nodes.add(node);
        }
    }

    // iterate through each node and wrap with <something> tag
    for (Node node : nodes) {
        // remember the next sibling for inserting at end
        Node nextSibling = node.getNextSibling();

        // remember the parent and remove this node from it
        Node parent = node.getParentNode();
        parent.removeChild(node);

        // create <something> element and attach node
        Element element = doc.createElement("something");
        NamedNodeMap attributes = element.getAttributes();
        Attr attr = doc.createAttribute("style");
        attr.setNodeValue("background-color:red");
        attributes.setNamedItem(attr);
        element.appendChild(node);

        // insert new element where the node was 
        parent.insertBefore(element, nextSibling);
    }
}

If you want to exclude any nodes then just filter them out in the first for loop.

许久 2024-11-01 09:27:18

我想向您建议一个递归解决方案,它利用 Node#replaceChild 方法用新标签替换节点:

public static void paintAllNodes(Node node) {
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element somethingElement = node.getOwnerDocument().createElement("something");
        somethingElement.setAttribute("style", "background-color:red");
        node.getParentNode().replaceChild(somethingElement, node);
        somethingElement.appendChild(node);
        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            paintAllNodes(nodeList.item(i));
        }
    }
}

这是我的主要:

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("document.xml"));
    paintAllNodes(document.getDocumentElement());

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(document);
    StreamResult result = new StreamResult(System.out);
    transformer.transform(source, result);
}

我已经使用此 xml 对其进行了测试:

<html>
    <head>
        <title>title</title>
    </head>
    <body>
    <h1>title</h1>
    <div>test</div>
    </body>
</html>

我的main 已打印出这个新的 xml,这似乎就是您想要的:

<?xml version="1.0" encoding="UTF-8"?><something style="background-color:red"><html>
    <something style="background-color:red"><head>
        <something style="background-color:red"><title>title</title></something>
    </head></something>
    <something style="background-color:red"><body>
    <something style="background-color:red"><h1>title</h1></something>
    <something style="background-color:red"><div>test</div></something>
    </body></something>
</html></something>

希望这会有所帮助。

I'd like to propose you a recursive solution, which make use of Node#replaceChild method to replace a node with a new tag:

public static void paintAllNodes(Node node) {
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element somethingElement = node.getOwnerDocument().createElement("something");
        somethingElement.setAttribute("style", "background-color:red");
        node.getParentNode().replaceChild(somethingElement, node);
        somethingElement.appendChild(node);
        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            paintAllNodes(nodeList.item(i));
        }
    }
}

This is my main:

public static void main(String[] args) throws SAXException, IOException,
        ParserConfigurationException, TransformerException {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document document = docBuilder.parse(new File("document.xml"));
    paintAllNodes(document.getDocumentElement());

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(document);
    StreamResult result = new StreamResult(System.out);
    transformer.transform(source, result);
}

I've tested it with this xml:

<html>
    <head>
        <title>title</title>
    </head>
    <body>
    <h1>title</h1>
    <div>test</div>
    </body>
</html>

My main has printed out this new xml, which seems to be what you want:

<?xml version="1.0" encoding="UTF-8"?><something style="background-color:red"><html>
    <something style="background-color:red"><head>
        <something style="background-color:red"><title>title</title></something>
    </head></something>
    <something style="background-color:red"><body>
    <something style="background-color:red"><h1>title</h1></something>
    <something style="background-color:red"><div>test</div></something>
    </body></something>
</html></something>

Hope this helps.

云裳 2024-11-01 09:27:18

作为非答案;-)我建议使用 CSS...something {background:red}
显然,只有当你使用 CSS 时这才有意义。

As a non-answer ;-) I propose to use CSS... something {background:red}
Obviously, this only makes sense if you use CSS anyways.

感性 2024-11-01 09:27:18

对于任何给定的节点“node”,以及它来自类似的文档“document”,应该可以工作。

Node parent = node.getParent();
Node nextSibling = node.getNextSibling();

parent.removeChild(node);

Element something = document.createElement("something");
NamedNodeMap atts = something.getAttributes();
Attr att = document.createAttribute("style");
att.setNodeValue("background-color:red;");
atts.setNamedItem(att);
something.addChild(node);
parent.insertBefore(something, nextSibling);

For any given node 'node', and the document 'document' it came from something like this should work.

Node parent = node.getParent();
Node nextSibling = node.getNextSibling();

parent.removeChild(node);

Element something = document.createElement("something");
NamedNodeMap atts = something.getAttributes();
Attr att = document.createAttribute("style");
att.setNodeValue("background-color:red;");
atts.setNamedItem(att);
something.addChild(node);
parent.insertBefore(something, nextSibling);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文