0

次の XML ファイルを読みたい:

<RootNode>
    <Node id="1"> value1 </Node>
    <Node id="2"> value2 </Node>
    <Node id="3"> value3 </Node>
    <Node id="4"> value4 </Node>
    <Node1 id="1"> value11 </Node1>
    <Node1 id="2"> value12 </Node2>
    ...
</RootNode>

ノードIDに応じて、値を取得したい。同様に、ノード名がNodeで id が1値である必要がvalue1あり、ノード名がNode1で id である2場合、値は である必要がありますvalue12

Nodeこのコードを使用して、名前を持つ要素を取得できます。

try{
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlString));
    Document doc = db.parse(is);
    NodeList nodes = doc.getElementsByTagName("Node");
}
catch(Execption e){
    e.printStacktrace();
}

id属性 (この場合) に応じて要素を取得するにはどうすればよいですか?

4

3 に答える 3

2

id の値を確認するには、最初に属性 'id' 値を取得します

private static String getAttributeValue(final Node node, final String attributeName) {
    Element element = (Element) node;
    return element.getAttribute(attributeName);
}


このように node(name = 'node') と attribute name('id') をこのメソッドに渡すと、属性 id の値が返されます。これで、値とノードができたので、やりたいことが何でもできます:)

ノードリストを反復するには

for (int i = 0; i < nodeList.getLength(); i++) {
    Node node = nodeList.item(i);
}
于 2013-07-05T05:21:33.733 に答える
0

このコードを使用

for (int i = 0; i < nodes.getLength(); i++) {
      NamedNodeMap parmAttrMap = parmList.item(i).getAttributes();
      if ((parmAttrMap.getNamedItem("id") != null)) {
         //get value of id -- parmAttrMap.getNamedItem("id");
  }
}
于 2013-07-05T05:21:53.780 に答える