0

我是 Java 新手,需要一些帮助。我有一个看起来像这样的 XML:

String pXML =
"<root>
     <x>1</x>
     <x>2</x>
     <x>3</x>
     <x>4</x>
 </root>"

我想得到一个 List 对象,其中包含 x 标记内的所有值。

我试过 javax.xml.parsers.DocumentBuilderFactory:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
DocumentBuilder builder = factory.newDocumentBuilder();
document = (Document) builder.parse( new InputSource( new StringReader(pXML) ) );
Node n = document.getFirstChild();
NodeList n1 = n.getChildNodes();
//and then I go through all the nodes and insert the values into a list

但这不包含 x 节点。

4

3 回答 3

3

您可以使用 XPath 获取所有x节点的值,如下所示:

public static void main(String[] args) throws SAXException, ParserConfigurationException, IOException, XPathExpressionException {
    final String pXML = "<root><x>1</x><x>2</x><x>3</x><x>4</x></root>";
    final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(pXML.getBytes()));
    final XPathExpression xPathExpression = XPathFactory.newInstance().newXPath().compile("//x/text()");
    final NodeList nodeList = (NodeList) xPathExpression.evaluate(document, XPathConstants.NODESET);
    final List<String> values = new LinkedList<>();
    for (int i = 0; i < nodeList.getLength(); ++i) {
        values.add(nodeList.item(i).getNodeValue());
    }
    System.out.println(values);
}

输出:

[1, 2, 3, 4]

这具有作为一个非常通用的解决方案的优点,如果 XML 的结构发生变化,它很容易适应。

在我看来,它还具有比手动迭代节点更容易理解的优点Document

于 2013-03-26T13:51:53.040 回答
0

尝试这个

import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XML {
  public static void main(String arg[]) throws Exception{
    String xmlRecords = "<root><x>1</x><x>2</x><x>3</x><x>4</x></root>";

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlRecords));

    Document doc = db.parse(is);
    NodeList nodes = doc.getElementsByTagName("x");
    System.out.println(nodes.getLength());
    List<String> valueList = new ArrayList<String>();
    for (int i = 0; i < nodes.getLength(); i++) {
      Element element = (Element) nodes.item(i);

      String name = element.getTextContent();

     // Element line = (Element) name.item(0);
      System.out.println("Name: " + name);
      valueList.add(name);
    }

  }
}
于 2013-03-26T14:56:09.167 回答
0

尝试Node n = document.getDocumentElement();恢复 XML 的根元素

于 2013-03-26T13:46:34.413 回答