打印XML节点属性值有问题

时间:2013-05-19 13:31:53

标签: java xml xpath

我在打印给定XML文件中的节点中存在的属性的值时遇到问题。我使用该代码并且编译正确但没有打印任何内容:

XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//rss/channel/yweather:location/@city");
Object result = expr.evaluate(doc, XPathConstants.STRING);
System.out.println(result);

,XML文件为:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
<channel>
  <title>Yahoo! Weather - Sunnyvale, CA</title>
  <link>http://us.rd.yahoo.com/dailynews/rss/weather/Sunnyvale__CA/*http://weather.yahoo.com/forecast/USCA1116_f.html</link>
  <description>Yahoo! Weather for Sunnyvale, CA</description>
  <language>en-us</language>
  <lastBuildDate>Fri, 18 Dec 2009 9:38 am PST</lastBuildDate>
  <ttl>60</ttl>
  <yweather:location city="Sunnyvale" region="CA"   country="United States"/>
  <yweather:units temperature="F" distance="mi" pressure="in" speed="mph"/>
</channel>
</rss>

1 个答案:

答案 0 :(得分:2)

以下代码适用于xpath中的命名空间引用。关键点是实施NamespaceContext并致电domFactory.setNamespaceAware(true) ...

import java.util.Iterator;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;

public class Demo 
{
    public static void main(String[] args) 
    {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        try 
        {
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            Document dDoc = builder.parse("c:\\path\\to\\xml\\file.xml");
            XPath xPath = XPathFactory.newInstance().newXPath();
            xPath.setNamespaceContext(new UniversalNamespaceResolver(dDoc));
            String query = "//rss/channel/yweather:location/@city";
            XPathExpression expr = xPath.compile(query);
            Object result = expr.evaluate(dDoc, XPathConstants.STRING);
            System.out.println(result);
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
    }

    public static class UniversalNamespaceResolver implements NamespaceContext 
    {
        private Document sourceDocument;

        public UniversalNamespaceResolver(Document document) 
        {
            sourceDocument = document;
        }

        public String getNamespaceURI(String prefix) 
        {
            if (prefix.equals(XMLConstants.DEFAULT_NS_PREFIX))
                return sourceDocument.lookupNamespaceURI(null);
            else
                return sourceDocument.lookupNamespaceURI(prefix);
        }

        public String getPrefix(String namespaceURI) 
        {
            return sourceDocument.lookupPrefix(namespaceURI);
        }

        public Iterator getPrefixes(String namespaceURI) 
        {
            return null;
        }
    }   
}

请务必在运行前更改文件路径。