如何在JAVA中获取XML文件的特定字段名称?

时间:2014-03-14 06:38:29

标签: java xml xml-parsing stax

您好我是STAX的新手,我以xml文件为例。喜欢这个

<?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>

我只想要一个名称,其敏感值是真的。在这个例子中,我只想要Name,ssn,emailid和bankaccount数字。那我该怎么办?请有人帮助我。

2 个答案:

答案 0 :(得分:0)

使用DOM要容易得多。你可以在这里参考:http://www.developerfusion.com/code/2064/a-simple-way-to-read-an-xml-file-in-java/。希望可以帮到你

答案 1 :(得分:0)

使用dom4j。以下示例代码可以帮助您:

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

    }

}