在 Java 中使用 XPath 解析 XML [英] parsing XML using XPath in Java

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

问题描述

假设我有以下 XML 文件:

Say I have the following XML file:

<?xml version="1.0" encoding="utf-8"?>
<venues>
  <group type="Nearby">
    <venue>
      <id>222307</id>
      <name>Union Chapel</name>
      <primarycategory>
        <id>78967</id>
        <fullpathname>Arts &amp; Entertainment:Music Venue</fullpathname>
        <nodename>Music Venue</nodename>
        <iconurl>http://foursquare.com/img/categories/arts_entertainment/musicvenue.png</iconurl>
      </primarycategory>
      <address>Compton Ave</address>
      <city>Islington</city>
      <state>Greater London</state>
      <zip>N1 2XD</zip>
      <verified>false</verified>
      <geolat>51.5439732</geolat>
      <geolong>-0.1020908</geolong>
      <stats>
        <herenow>0</herenow>
      </stats>
      <phone>02073594019</phone>
      <distance>33</distance>
    </venue>

........

我的代码如下:

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile("//venue/*");

    Object result = expr.evaluate(document, XPathConstants.NODESET);
    NodeList nodes = (NodeList) result;
    //System.out.println(nodes.getLength());

    Venue ven = new Venue();

    for (int i = 0; i < nodes.getLength(); i++) {
        String nodeName = nodes.item(i).getNodeName();
        String nodeValue = nodes.item(i).getNodeValue();


        if (nodeName.equals("id")){
            ven = new Venue();
            if (nodeValue != null)
                ven.id = Integer.parseInt(nodeValue);
            System.out.println(ven.id);
        }

        if (nodeName.equals("name")){
            ven.name = nodeValue;
            System.out.println(ven.name);
        }

        if (nodeName.equals("address")){
            ven.address = nodeValue;
            System.out.println(ven.address);
        }

如何在一个 for 循环中完成所有这些工作以提高效率?否则,对于我想要提取的 xml 中的每个属性,我需要为每个属性创建一个 for 循环

How can I do all of this in one for loop for efficiency? Otherwise for every attribute in the xml that I want to extract I need to create a for loop for each one of them

推荐答案

如果您将其用作 xpath:

If you use this as your xpath:

//venue/*

您将获得场地的所有子节点.然后你可以迭代这个,在节点名称上做一个大的 if else 并根据需要分配它们.

You'll get all the child nodes of venue. You can then iterate over this and do a big if else on the node name's and assign them as needed.

像这样:

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//venue/*");

Object result = expr.evaluate(document, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item( i );
            String nodeName = node.getNodeName();
            String nodeValue = node.getChildNodes().item( 0 ).getNodeValue();


            if( nodeName.equals( "name" ) ) {
                        name = nodeValue;
            } 
            else if( nodeName.equals( "address" ) ) {
                        address = nodeValue;
            } // ... the rest goes here
}

如果你不想遍历所有子元素,你可以这样做:

If you don't want to iterate over all child elements you could do something like this:

    XPathExpression expr = xpath.compile( "//venue" );

    Object result = expr.evaluate( document, XPathConstants.NODESET );
    NodeList nodes = (NodeList)result;
    for( int i = 0; i < nodes.getLength(); i++ ) {
        Node node = nodes.item( i );
        NodeList venueChildNodes = node.getChildNodes();

        String id = venueChildNodes.item( 1 ).getChildNodes().item( 0 ).getNodeValue();
        System.out.println( "id: " + id );

        String name = venueChildNodes.item( 3 ).getChildNodes().item( 0 ).getNodeValue();
        System.out.println( "name: " + name );

        String address = venueChildNodes.item( 7 ).getChildNodes().item( 0 ).getNodeValue();
        System.out.println( "address: " + address );
    }

获取所有场地节点,然后将其映射到子节点的位置.但是,这种方法需要相当一致的 xml 结构.不过,这样的事情对我来说似乎最安全:

Where you get all venue nodes and then map it's children. Though, this approach would require a fairly consistent xml structure. Though, something like this seems safest to me:

    XPathExpression expr = xpath.compile( "//venue" );

    Object result = expr.evaluate( document, XPathConstants.NODESET );
    NodeList nodes = (NodeList)result;
    for( int i = 0; i < nodes.getLength(); i++ ) {
        Node node = nodes.item( i );
        NodeList venueChildNodes = node.getChildNodes();

        String address = null;
        String name = null;

        for( int j = 0; j < venueChildNodes.getLength(); j++ ) {
            Node item = venueChildNodes.item( j );
            String nodeName = item.getNodeName();

            if ( nodeName.equals( "address" ) ) {
                address = item.getChildNodes().item( 0 ).getNodeValue();
            }

            if ( nodeName.equals( "name" ) ) {
                name = item.getChildNodes().item( 0 ).getNodeValue();
            }
        }

        System.out.println( "address: " + address );
        System.out.println( "name: " + name );
    }

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

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