Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem using XPath to Parse XML String Data

Tags:

java

xml

xpath

I'm trying to use XPath to parse an XML string but I am getting only null values back. Does anyone have an idea where I might be going wrong in the code shown below?

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));
    }
}

The output from System.out is 'value=[URL128: null]', but it should be the URL I am trying to extract: http://cachens.corbis.com/CorbisImage/thumb/15/53/42/15534232/42-15534232.jpg.

Any help appreciated, thanks.

like image 301
c12 Avatar asked Apr 19 '26 02:04

c12


1 Answers

What if you try changing your XPath evaluation statement from this:

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

to this:

list = (NodeList) xPath.evaluate("//URL128/@Value", 
    source, XPathConstants.NODESET);
like image 75
Hovercraft Full Of Eels Avatar answered Apr 20 '26 16:04

Hovercraft Full Of Eels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!