0

私はJavaを初めて使用するので、助けが必要です。次のようなXMLがあります。

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

そして、xタグ内のすべての値を含むListオブジェクトを取得したいと思います。

私は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

Node n = document.getDocumentElement();XMLのルート要素を回復してみてください

于 2013-03-26T13:46:34.413 に答える
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 に答える