使用Java DOM获取XML文本值

时间:2015-07-01 14:19:34

标签: java xml

尝试从“value”属性中获取文本。我如何使用Java DOM做到这一点?我稍后将不得不浏览数以千计的* .xml文件,它们是这个大20倍的文件并查找“failing_message”,然后需要获取其failing_message,即“value”属性。

<?xml version="1.0" encoding="UTF-8"?>
<root version="14" libraryDocVersion="17">
  <node type="flow" id="3224122a-b164-422c-add2-974f22229b6a">
    <child name="inputs">
      <collection type="list">
        <node type="staticBinding" id="3333333-9dd4-4363-9f15-1333c433335">
                <attribute name="annotation"></attribute>
                <attribute name="assignFromContext">false</attribute>
                <attribute name="assignToContext">false</attribute>
                <attribute name="inputSymbol">failing_message</attribute>
                <attribute name="inputType">String</attribute>
                <attribute name="isList">false</attribute>
                <attribute name="isPersisted">true</attribute>
                <attribute name="last_modified_by">admin</attribute>
                <attribute name="listDelimiter">,</attribute>
                <attribute name="modifiedTimestamp">1428938670220</attribute>
                <attribute name="record">false</attribute>
                <attribute name="required">true</attribute>
                <attribute name="uuid">3333333-30c4-3333-3333-333800d10333</attribute>
                <attribute name="value">Could not get free IP address for installation</attribute>
         </node>
       </collection>
    </child>
  </node>
</root>

2 个答案:

答案 0 :(得分:1)

您应该使用xpath来搜索XML文档。这是搜索加载的XML文档的最有效方法。

以下是为您提供attribute元素name="value"元素的文本值的代码

import javax.xml.parsers.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;

public static void main(String[] args)
{
    try {
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("C://Temp/xx.xml");

            XPath xPath =  XPathFactory.newInstance().newXPath();
            Node n = (Node)xPath.compile("//attribute[@name='value']")
                    .evaluate(doc, XPathConstants.NODE);
            System.out.println(n.getTextContent());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

输出

Could not get free IP address for installation

答案 1 :(得分:0)

对于简单的用例,你可以使用sax,因为它更快:

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParserFactory;

public class ValueHandler extends DefaultHandler{

    private boolean valueAttributeElement;
    private StringBuilder content = new StringBuilder();
    private String answer;

    @Override
    public void startElement(String uri, String localName, String qname, Attributes attributes) throws SAXException{
        valueAttributeElement = localName.equals("attribute") && "value".equals(attributes.getValue("name"));
        content.setLength(0);
    }

    @Override
    public void characters(char[] chars, int start, int length) throws SAXException{
        if(valueAttributeElement)
            content.append(chars, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String qname) throws SAXException{
        if(valueAttributeElement)
            answer = content.toString();
    }

    public String getAnswer(){
        return answer;
    }

    public static void main(String[] args) throws Exception{
        String file = "/Users/santhosh/tmp/jlibs-test/src/main/resources/test.xml";
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        ValueHandler valueHandler = new ValueHandler();
        factory.newSAXParser().parse(file, valueHandler);
        System.out.println("answer: "+valueHandler.getAnswer());
    }
}

输出是:

answer: Could not get free IP address for installation