-1

I have this XML:

<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope>
    <soapenv:Body>
        <response>
            <note identifier="4719b11c-230e-4533-b1a5-76ac1dc69ef7" hash="956F3D94-A8B375ED-BA15739F-387B4F5E-75C6ED82" dat_prij="2016-09-27T23:06:20+02:00"/>
            <item uid="9f9cb5fb-75e6-4a2f-be55-faef9533d9ff-ff" active="true"/>
        </response>
    </soapenv:Body>
</soapenv:Envelope>

I need parse item uid, in this case its value "9f9cb5fb...", but I dont know how to parse with Java standard nodes. Thank you for advice.

Edited: I tried this code, but not working:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(response));
    Document doc = builder.parse(is);

    Element root = doc.getDocumentElement();

    NodeList nList = doc.getElementsByTagName("soapenv:Envelope");
    NodeList body = nList.getElementsByTagName("soapenv:Body");
    NodeList resp = body.getElementsByTagName("response");


        Node node = nList.item("item");
        System.out.println("");    //Just a separator
        Element eElement = (Element) node;
        System.out.println(eElement.getAttribute("uid"));

1 Answers1

2

Using DOM:

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(response));
    Document doc = builder.parse(is);

    NodeList nList = doc.getElementsByTagName("item");
    Node namedItem = nList.item(0).getAttributes().getNamedItem("uid");
    System.out.println(namedItem.getNodeValue());

Using SAX:

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();

    DefaultHandler handler = new DefaultHandler() {

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            if (qName.equals("item")) {
                System.out.println(attributes.getValue("uid"));
            }
        }
    };

    saxParser.parse(new InputSource(new StringReader(response)), handler);

You may want to read some tutorials about XML, DOM and SAX: https://docs.oracle.com/javase/tutorial/jaxp/dom/readingXML.html https://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html

Or you can just use Regex and some string replacing:

    Pattern pattern = Pattern.compile("uid=\"[^\"]*\"");
    Matcher matcher = pattern.matcher(response);
    if(matcher.find()) {
        String attr = matcher.group();
        attr = attr.replace("\"", "");
        attr = attr.replace("uid=", "");
        System.out.println(attr);
    }

Note:

your XML isn't valid SOAP message. It's missing some namespaces declaration - no soapenv prefix is declared, and your elements and attributes are undefined.

MGorgon
  • 2,547
  • 23
  • 41