Pregunta

i want to parse an XML with SAX-Parser and find a node which contains special content.

Example XML:

<root>
     <someElement>
            #hashKey1
     </someElement>
     <someElement>
            value1
     </someElement>
     <someElement>
            #hashKey2
     </someElement>
     <someElement>
            value2
     </someElement>
     <someElement>
            #hashKey3
     </someElement>
     <someElement>
            value3
     </someElement>
</root>

The problem is, that i don't know what kind of node/element it is, where my content is in. i just want to find the first element/node which contains my content.

Do i have to write my own function "findNodeByContent" or is there a SAX-Parser implementation which offers such a function?

¿Fue útil?

Solución 2

You will have to create your own method that loops over the nodes. Unless I'm wrong there is no DOM method like getElementByValue.

Otros consejos

Use the Xpath support in JDK instead of SAX. You can find the element with this expression

//*[contains(text(), 'value2')]

It will find all elements that has a text node that contains the text 'value2'.

Here is some sample code:

    XPath p = XPathFactory.newInstance().newXPath();
    InputSource in = new InputSource(...);
    NodeList list = (NodeList) p.evaluate("//*[contains(text(), 'value2')]", in, XPathConstants.NODESET);
    for(int i=0; i < list.getLength(); ++i) {
        System.out.println(list.item(i));
    }

try with this code..

public class SaxParser extends DefaultHandler {
    public void parse(String xmlName) throws ParserConfigurationException,
            SAXException, IOException {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        SaxParser parser = new SaxParser();
        saxParser.parse("src/test.xml", parser);

    }

    public void characters(char[] buffer, int start, int length) {
        String text = new String(buffer, start, length);
        System.out.println(text);
        if(text.trim().equals("your value")){
            // your action
        }
    }

    public void startElement(String uri, String localName, String qName,
            Attributes attributes) {
    }

    public void endElement(String uri, String localName, String qName) {

    }

    public static void main(String[] a) throws ParserConfigurationException,
            SAXException, IOException {
        new SaxParser().parse("src/test.xml");
    }

}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top