0

如何使用循环解析/获取位置节点值:印度新德里,以及如何从该 xml 文件中获取多个教育节点值,如 SVM、HHHHH 等。XML:

<?xml version="1.0" encoding="UTF-8"?>
<facebookfriends>
<data>
<id>
[Removed]
    </id>
    <location>
        <id>
            [Removed]
        </id>
        <name>
            New Delhi, India
        </name>
    </location>
    <name>
        XYZZZZZZZZZZ
    </name>
    <education>
        <school>
            <id>
                [Removed]
            </id>
            <name>
                SVM
            </name>
        </school>
        <year>
            <id>
                [Removed]
            </id>
            <name>
                2001
            </name>
        </year>
        <type>
            High School
        </type>
    </education>
    <education>
        <concentration>
            <id>
                [Removed]
            </id>
            <name>
                Computer Science
            </name>
        </concentration>
        <school>
            <id>
                [Removed]
            </id>
            <name>
                HHHHHHHHHHHHH
            </name>
        </school>
        <type>
            Graduate School
        </type>
</education>
</data>

</facebookfriends>
4

2 回答 2

1

您可以为此使用jDom ..简单易用...

http://www.mkyong.com/java/how-to-read-xml-file-in-java-jdom-example/

有关示例,请参见上面的链接...

于 2013-09-26T08:19:51.300 回答
0

下面的代码将帮助您通过解析从 xml 获取位置/名称节点值。同样,您只需更改 xpath 即可获取其他节点值。

        File xmlFile = new File("C:/face.xml");
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        try{
            builder = builderFactory.newDocumentBuilder();
            Document document = builder.parse(xmlFile);
            XPath xPath = XPathFactory.newInstance().newXPath();
            String exp = "/facebookfriends/data/location/name";
            NodeList nodeList = (NodeList) xPath.compile(exp).evaluate(document, XPathConstants.NODESET);
            for (int i = 0; i < nodeList.getLength(); i++) {
                System.out.println(nodeList.item(i).getFirstChild().getNodeValue()); 
            }
        }catch (ParserConfigurationException e) {
            e.printStackTrace();  
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
于 2015-06-29T10:26:52.757 回答