1

Hello i am new to STAX and I have xml file as an example. Like this

<?xml version="1.0"?>
<data>
<name>
<sensitive>true</sensitive>
    </name>

<dob>
<sensitive>false</sensitive>
</dob>

<email-id>
<sensitive>true</sensitive>
</email-id>

<ssn>       
<sensitive>true</sensitive>
</ssn>

<bankaccountnumber>
<sensitive>true</sensitive>
</bankaccountnumber>

<licencenumber>
<sensitive>false</sensitive>
</licencenumber>

I want just feild name , whose sensitive value is true. In this example i want just Name,ssn, emailid and bankaccount number. So how can i do. Please anyone help me.

Brijesh Patel
  • 33
  • 1
  • 1
  • 5
  • 1
    Use [`DocumentBuilder`](http://docs.oracle.com/javase/7/docs/api/javax/xml/parsers/DocumentBuilder.html) to parse, then use the DOM methods to navigate the document tree and search for the values you need. A simple example of parsing XML can be found here: http://stackoverflow.com/questions/21963137/parsing-xml-file-contents-without-knowing-xml-file-structure/21963189#21963189. Alternately, you could find the elements with an XPath query, see http://stackoverflow.com/questions/2811001/how-to-read-xml-using-xpath-in-java. – Jason C Mar 14 '14 at 06:42
  • Ohh ones again thanx Jason . – Brijesh Patel Mar 14 '14 at 06:45

2 Answers2

0

It is much more easier to use DOM. You can refer here : http://www.developerfusion.com/code/2064/a-simple-way-to-read-an-xml-file-in-java/ . Hope can help you

Newbie
  • 3
  • 2
0

Use dom4j. Here is sample code that may help you :

private List<String> _listXPath = new ArrayList<String>();
public static void main(String[] args) {

      Document document = DocumentHelper.parseText(xml);

      treeWalk(document);
}

    private void treeWalk(Document document) {
        treeWalk( document.getRootElement() );
}

 // Traverse xml
private void treeWalk(Element element) {
    String line = "";

    for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
        Node node = element.node(i);

        if ( node instanceof Element ) {

            Element el = (Element) node;

             for ( int j = 0, total = el.attributeCount(); j < total; j++ ) {

                 Attribute attribute =  el.attribute(j);

                 line = attribute.getPath() + attribute.getValue();

                 _listXPath.add(line); 
             }

            treeWalk( (Element) node );
        }
        else {


             line = node.getPath() +node.getText();

            _listXPath.add(line);
        } 

    }

}
Stathis Andronikos
  • 1,259
  • 2
  • 25
  • 44