英文:
Xpath read given attribute tag value
问题
Sure, here is the translated code part:
String exp = "//MS_xml_root/message/field";
NodeList list = (NodeList) xPath.compile(exp).evaluate(doc, XPathConstants.NODESET);
for (int i = 0; i < list.getLength(); i++) {
// 需要在这里读取值。
}
Please let me know if you need any further assistance with this code.
英文:
<?xml version="1.0" encoding="UTF-8"?>
<MS_xml_root>
<message>
<field id="A">A</field>
<field id="B">B</field>
<field id="C"></field>
</message>
<message>
<field id="A">A</field>
<field id="B">B</field>
<field id="C"></field>
</message>
</MS_xml_root>
I want to read the field tag value by giving the field id key using XPath. But I can read the attribute value.
String exp = "//MS_xml_root/message/field"
NodeList list = (NodeList) xPath.compile(exp).evaulate(doc,XPathConstants.NODESET);
for(int i=0;i < list.getLength(); i++){
//need to read the value here.
}
答案1
得分: 1
String id = "A";
String exp = "//MS_xml_root/message/field[@id='" + id + "']";
将获取具有 id="A"
的节点。要获取属性值,可以使用以下方式:
String exp = "//MS_xml_root/message/field/@id";
英文:
String id = "A";
String exp = "//MS_xml_root/message/field[@id='" + id + "']";
will get the nodes with id="A"
. Use NODE
instead of NODESET
to get a single Node
.
If you want the attribute value, use something like:
String exp = "//MS_xml_root/message/field/@id";
答案2
得分: 1
看起来您需要获取具有特定ID的节点的TextContent的Java方法。
您可以使用以下代码来实现:
private static List<String> getFieldNodeValues(Document doc, String id) throws XPathExpressionException {
String exp = "//MS_xml_root/message/field[@id='" + id + "']";
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList list = (NodeList) xpath.compile(exp).evaluate(doc, XPathConstants.NODESET);
List<String> res = new ArrayList<>();
for (int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
res.add(node.getTextContent());
}
return res;
}
您可能需要的是值的列表,而不仅仅是一个值,因为您的XML似乎对于给定的ID值有多个字段。
英文:
It seems you need the Java method to get the TextContent of nodes which have a specific ID.
You could do it with below code:
private static List<String> getFieldNodeValues(Document doc, String id) throws XPathExpressionException {
String exp = "//MS_xml_root/message/field[@id=" + "\"" + id + "\"" + "]";
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList list = (NodeList) xpath.compile(exp).evaluate(doc,XPathConstants.NODESET);
List<String> res = new ArrayList<>();
for ( int i = 0; i < list.getLength(); i++ ) {
Node node = list.item(i);
res.add(node.getTextContent());
}
return res;
}
You may want a list of values not one value, because your xml seems to have more than one field for a given ID value.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论