java
  • xml
  • xpath
  • 2011-08-10 34 views 3 likes 
    3

    我想使用XPath来解析XML字符串,但我只收到空值。有没有人有一个想法,我可能会在下面显示的代码出错?使用XPath来解析XML字符串数据的问题

    public static void main(String[] args) { 
        String content = "<imagesXML><Images><Image><ImageUID Scope='Public' Type='Guid' Value='{7f2535d0-9a41-4997-9694-0a4de569e6d9}'/><CorbisID Scope='Public' Type='String' Value='42-15534232'/><Title Scope='Public' Type='String' Value='Animal'/><CreditLine Scope='Public' Type='String' Value='© Robert Llewellyn/Corbis'/><IsRoyaltyFree Scope='Public' Type='Boolean' Value='False'/><AspectRatio Scope='Public' Type='String' Value='1.500000'/><URL128 Scope='Public' Type='String' Value='http://cachens.corbis.com/CorbisImage/thumb/15/53/42/15534232/42-15534232.jpg'/></Image></Images></imagesXML>"; 
        InputSource source = new InputSource(new StringReader(content)); 
        XPath xPath = XPathFactory.newInstance().newXPath(); 
        NodeList list = null; 
        try { 
         list = (NodeList) xPath.evaluate("//URL128[@Value]", source, 
           XPathConstants.NODESET); 
        } catch (Exception ex) { 
         System.out.println(ex.getMessage()); 
        } 
        for (int i = 0; i < list.getLength(); i++) { 
         System.out.println(list.item(i)); 
        } 
    } 
    

    从System.out的输出是“值= [URL128:空]”,但它应该是我试图提取的网址:http://cachens.corbis.com/CorbisImage/thumb/15/53/42/15534232/42-15534232.jpg

    任何帮助表示感谢,谢谢。

    回答

    5

    如果你尝试从这个改变你的XPath评价声明:

    list = (NodeList)xPath.evaluate("//URL128[@Value]", 
        source, XPathConstants.NODESET); 
    

    这样:

    list = (NodeList) xPath.evaluate("//URL128/@Value", 
        source, XPathConstants.NODESET); 
    
    +0

    谢谢,这工作。我得到价值=“http://cachens.corbis.com/CorbisImage/thumb/15/53/42/15534232/42-15534232.jpg” 有什么办法可以使用XPath评估去除Value =部分吗? – c12

    +0

    ahhh,知道了System.out.println(list.item(i).getTextContent()); – c12

    +0

    @ c12:当然,如果你知道它不会在String的主体中表示,那么你可以用'String#replace'或'String#replaceAll'来实现。 - 没关系,你的方式更好! –

    1

    注:

    • //URL128[@Value]返回所有URL123的列表中的表达式具有Value属性的元素
    • //URL128/@Value在源

    无论这些列表的包含字符串返回从每个URL128元件Value属性的列表中的表达;它们包含DOM类型。您的源中只有一个URL128元素,但您要求提供NodeList。你可以通过使用以下简化:

    String url = xPath.evaluate("//URL128/@Value", source); 
    
    相关问题