简体   繁体   English

从Java中的xml中提取特定元素

[英]extract specific element from xml in java

How can I extract a block of data from an XML file by element name, or delete all content of an XML file except for one element and all its child nodes? 如何通过元素名称从XML文件提取数据块,或删除XML文件中除一个元素及其所有子节点之外的所有内容?

I am new to Java, I have tried with XPath but did not get what I wanted to have. 我是Java的新手,我曾经尝试过XPath,但没有得到想要的东西。

You do not to delete anything. 您不删除任何内容。 By XPath you need to transverse to the element you needed. 通过XPath,您需要横向于所需的元素。 Another thing is Xpath has nothing to do with the language you are using for scripting. 另一件事是Xpath与您用于脚本编写的语言无关。 It can be java, python, C#, ruby etc. 它可以是java,python,C#,ruby等。

To learn more about Xpath refer below link :- 要了解有关Xpath的更多信息,请参考以下链接:-

http://www.w3schools.com/xsl/xpath_intro.asp http://www.w3schools.com/xsl/xpath_intro.asp

Hope it will help you :) 希望它能对您有所帮助:)

test .... .... 测试.....

here is the sample code to get ID element content expressions public static final String IdExpr = "/NameDefinition/@Id"; 这是获取ID元素内容表达式的示例代码public static final String IdExpr =“ / NameDefinition / @ Id”;

String evaluateXML(String file, String IdExpr) { 字符串评估XML(字符串文件,字符串IdExpr){

Stringres= null;
try {
    FileInputStream fis = new FileInputStream(new File(file));

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory
        .newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document xmlDocument = builder.parse(fis);

    XPath xPath = XPathFactory.newInstance().newXPath();

    String Id = xPath.compile(IdExpr).evaluate(
            xmlDocument);




    return Id;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM