使用java解析器删除XML节点 [英] Remove XML Node using java parser

查看:508
本文介绍了使用java解析器删除XML节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的示例XML中,如何使用java解析器删除整个B节点(如果E = 13)。

In the below sample XML, how to remove Entire B Node if E=13 using java parser.

<xml>
   <A>
     <B>
       <C>
         <E>11</E>
         <F>12</F>
       </C>
    </B>
    <B>
       <C>
         <E>13</E>
         <F>14</F>
      </C>
    </B>
  </A>

请告知。

推荐答案

替代DOM方法

或者,您可以使用XPath而不是对XML文档进行强力遍历JDK中的功能,找到值为13的B元素,然后将其从父项中删除:

Alternatively, instead of doing a brute force traversal of the XML document you could use the XPath capabilities in the JDK to find the "B" element with value "13" and then remove it from its parent:

import java.io.File;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import org.w3c.dom.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Document document = dbf.newDocumentBuilder().parse(new File("input.xml"));

        XPathFactory xpf = XPathFactory.newInstance();
        XPath xpath = xpf.newXPath();
        XPathExpression expression = xpath.compile("//A/B[C/E/text()=13]");

        Node b13Node = (Node) expression.evaluate(document, XPathConstants.NODE);
        b13Node.getParentNode().removeChild(b13Node);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.transform(new DOMSource(document), new StreamResult(System.out));
    }

}

使用XPath的优点是更容易维护,如果结构发生变化,它只需对代码进行一行更改。此外,如果文档的深度增加,基于XPath的解决方案保持相同的行数。

The advantage of using an XPath it's easier to maintain, if the structure changes it's just a one line change to your code. Also if the depth of your document grows the XPath based solution stays the same number of lines.

非DOM方法

如果您不想将XML实现为DOM。您可以使用Transformer和样式表来删除节点:

If you don't want to materialize your XML as a DOM. You could use a Transformer and a stylesheet to remove a node:

  • http://download.oracle.com/javase/6/docs/api/javax/xml/transform/Transformer.html

这篇关于使用java解析器删除XML节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆