简体   繁体   English

从子元素创建XPath

[英]Create XPath from Child Elements

I want to add an XPath attribute to all <definition> tags in my XML document. 我想将XPath属性添加到XML文档中的所有<definition>标记中。 The XPath's value will come from a nested tag <term>Test123</term> inside each <definition> tag. XPath的值将来自每个<definition>标记内的嵌套标记<term>Test123</term> I'm using the import org.w3c.dom.Document; 我正在使用import org.w3c.dom.Document; object. 宾语。 When I run this line with my really long XML file then it tells me that there are 539 instances of the <definition> tag: 当我使用非常长的XML文件运行此行时,它告诉我<definition>标记有539个实例:

System.out.println(inputDOM.getDocumentElement().getElementsByTagName("definition"));

So the end result is that there must be a Document object that has set all the definition tags from the term tags, for example 因此,最终结果是必须存在一个Document对象,该对象已设置了术语标签中的所有定义标签,例如

<definition XPath="Test123"> <term>Test123</term> </definition>

Try something like this 试试这个

NodeList definitionElements = inputDOM.getElementsByTagName("definition");
for (int i = 0; i < definitionElements.getLength(); i++) {
    Element current = (Element) definitionElements.item(i);
    Node term = current.getElementsByTagName("term").item(0);
    if(term != null && term.getNodeType() == Node.ELEMENT_NODE)
        current.setAttribute("XPath", ((Element) term).getTextContent());
}

First we get all <definition> tags. 首先,我们获得所有<definition>标签。 After that we iterate each <definition> tag and set a new attributs "XPath" whose value is the text content of the <term> child tag 之后,我们迭代每个<definition>标记并设置一个新属性“ XPath”,其值是<term>子标记的文本内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM