java - 如何使用 javax.xml.parsers.DocumentBuilder 只读取 xml 文件的一部分?

标签 java xml

<?xml version="1.0" encoding="UTF-8"?>

这是我的 test.xml 文件。我只想读取类节点的属性以及类节点下的所有属性。就像本例中的属性 name="billNo"。而不是根元素及其属性。我应该如何跳过读取根元素/?

最佳答案

入门示例:

xml 文件:

<inventory>
    <book year="2000">
        <title>Snow Crash</title>
        <author>Neal Stephenson</author>
        <publisher>Spectra</publisher>
        <isbn>0553380958</isbn>
        <price>14.95</price>
    </book>

    <book year="2005">
        <title>Burning Tower</title>
        <author>Larry Niven</author>
        <author>Jerry Pournelle</author>
        <publisher>Pocket</publisher>
        <isbn>0743416910</isbn>
        <price>5.99</price>
    </book>

    <book year="1995">
        <title>Zodiac</title>
        <author>Neal Stephenson</author>
        <publisher>Spectra</publisher>
        <isbn>0553573862</isbn>
        <price>7.50</price>
    </book>

    <!-- more books... -->

</inventory>

Java代码:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;


try {

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    Document doc = docBuilder.parse (new File("c:\\tmp\\my.xml"));

    // normalize text representation
    doc.getDocumentElement().normalize();
    System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());

    NodeList listOfBooks = doc.getElementsByTagName("book");
    int totalBooks = listOfBooks.getLength();
    System.out.println("Total no of books : " + totalBooks);

    for(int i=0; i<listOfBooks.getLength() ; i++) {

        Node firstBookNode = listOfBooks.item(i);
        if(firstBookNode.getNodeType() == Node.ELEMENT_NODE) {

            Element firstElement = (Element)firstBookNode;                              
            System.out.println("Year :"+firstElement.getAttribute("year"));

            //-------
            NodeList firstNameList = firstElement.getElementsByTagName("title");
            Element firstNameElement = (Element)firstNameList.item(0);

            NodeList textFNList = firstNameElement.getChildNodes();
            System.out.println("title : " + ((Node)textFNList.item(0)).getNodeValue().trim());
        }
    }//end of for loop with s var
} catch (SAXParseException err) {
    System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
    System.out.println(" " + err.getMessage ());
} catch (SAXException e) {
    Exception x = e.getException ();
    ((x == null) ? e : x).printStackTrace ();
} catch (Throwable t) {
    t.printStackTrace ();
}                

引用:How to read XML using XPath in Java

关于java - 如何使用 javax.xml.parsers.DocumentBuilder 只读取 xml 文件的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24735570/

相关文章:

java - 使用 HTMLParser 在 HTML 中插入标签

java - 传递给 List 的 ArrayAdapter 的 arraylist 应该是线程安全的吗?

java - 从泛型方法调用非泛型方法

java - 如何在 Eclipse 4.4 (Luna) 中添加 apache-tomcat 7

java - Hibernate子类id在每个子类的表中生成

sql-server - 将 Inserted 和 Deleted 行转换为 Xml 以供审计

python - 如何在 BeautifulSoup 中呈现 unicode 标签的内容?

Python 元素树 : find element by its child's text using XPath

javascript - 使用 ajax 比较两个 xml 值

xml - 找不到元素 'context:annotation-config' 的声明