解析XML并将结果存储在String中

时间:2014-03-13 12:36:50

标签: java xml string xpath

我真的很熟悉Java中的XML解析我已经使用Java成功读取了我的XML。现在的问题是我想用我的解析结果填充一个字符串。 我的代码:

 DocumentBuilderFactory builderFactory =
    DocumentBuilderFactory.newInstance();
 DocumentBuilder builder = null;
try {

builder = builderFactory.newDocumentBuilder();
        org.w3c.dom.Document document = builder.parse(
        new FileInputStream("c:\\y.xml"));

        XPath xPath =  XPathFactory.newInstance().newXPath();

       String expression = "/ADOXML/MODELS/MODEL/INSTANCE/ATTRIBUTE[@name='Description' and @type='STRING']";

NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
 int i;
for (i = 0; i < nodeList.getLength(); i++) {


 String txt=nodeList.item(i).getFirstChild().toString();
  System.out.print(txt);
}

System.out.print("\n\n\nIIIII="+i);

} catch (ParserConfigurationException | SAXException | IOException e) {
System.out.print(e);
}       

它给我的错误:

NodeList无法转换为Java.Lang.String!

所以我怎么能摆脱它可以有人帮助我!

1 个答案:

答案 0 :(得分:2)

我认为你想要String txt=nodeList.item(i).getTextContent();而不是String txt=nodeList.item(i).getFirstChild().toString();