使用XML属性读取Java中的XML

时间:2013-07-05 05:07:50

标签: java xml

我想阅读以下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,则值应为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)获取元素?

3 个答案:

答案 0 :(得分:2)

要检查id的值,请先获取属性'id'值

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


通过这种方式将节点(name ='node')和属性名称('id')传递给此方法,这将返回属性id的值。现在你有了价值,你有了节点,所以你可以做任何你想要的:)

迭代节点列表

for (int i = 0; i < nodeList.getLength(); i++) {
    Node node = nodeList.item(i);
}

答案 1 :(得分: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");
  }
}

答案 2 :(得分:0)

XPath可以帮助......

    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xmlString));
    Document doc = db.parse(is);
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("//Node[@id=\"YOUR_VALUE_HERE\"]");
    NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

将YOUR_VALUE_HERE替换为所需的id值,并迭代nl