gpt4 book ai didi

java - XML 将节点值解析为字符串

转载 作者:行者123 更新时间:2023-11-29 05:54:57 25 4
gpt4 key购买 nike

我的 xml 文件是这样的。我想像这样获取 value 节点文本内容。

<property regex=".*" xpath=".*">
<value>
127.0.0.1
</value>
<property regex=".*" xpath=".*">
<value>

</value>
</property>

我想按照他们在文件中指定的顺序获取文本。这是我的 Java 代码。

Document doc = parseDocument("properties.xml");
NodeList properties = doc.getElementsByTagName("property");
for( int i = 0 , len = properties.getLength() ; i < len ; i++) {
Element property = (Element)properties.item(i);
//How can i proceed further .
}

预期输出:

 Node 1 : 127.0.0.1

请提出您的看法。

最佳答案

以下方法查找所有property文档中的元素并收集所有 value那些名为 value 的元素的子元素不使用 XPath。

  private static List<Element> getValueElements(Document document) {
List<Element> result = new ArrayList<Element>();
NodeList propertyElements = document.getElementsByTagName("property");
for (int i = 0, ilen = propertyElements.getLength(); i < ilen; i++) {
Node propertyNode = propertyElements.item(i);
if (!(propertyNode instanceof Element))
continue;

NodeList children = ((Element) propertyNode).getChildNodes();
for (int j = 0, jlen = children.getLength(); j < jlen; j++) {
Node child = children.item(j);
if (!(child instanceof Element) || !"value".equals(child.getNodeName()))
continue;

result.add((Element) child);
}
}
return result;
}

但是您可以使用 XPath 表达式 //property/value 以更优雅的方式完成相同的操作:

private static List<Element> getValueElementsUsingXpath(Document document) throws XPathExpressionException {
XPath xpath = XPathFactory.newInstance().newXPath();
// XPath Query for showing all nodes value
XPathExpression expr = xpath.compile("//property/value");
Object xpathResult = expr.evaluate(document, XPathConstants.NODESET);

List<Element> result = new ArrayList<Element>();
NodeList nodes = (NodeList) xpathResult;
for (int i = 0; i < nodes.getLength(); i++) {
Node valueNode = nodes.item(i);
if (!(valueNode instanceof Element)) continue;
result.add((Element) valueNode);
}

return result;
}

你可以像这样使用上面的方法:

  public static void main(String[] args) throws Exception {
Document doc = parseDocument("properties.xml");
List<Element> valueElements = getValueElements(doc); // or getValueElementsUsingXpath(doc)

int nodeNumber = 0;
for (Element element : valueElements) {
nodeNumber++;
System.out.println("Node " + nodeNumber + ": " + formatValueElement(element));
}
}

private static String formatValueElement(Element element) {
StringBuffer result = new StringBuffer();

boolean first = true;
NodeList children = ((Element) element).getChildNodes();
for (int i = 0, len = children.getLength(); i < len; i++) {
Node child = children.item(i);

String childText = null;
switch (child.getNodeType()) {
case Node.CDATA_SECTION_NODE:
case Node.TEXT_NODE:
childText = child.getTextContent().trim();
}

if (childText == null || childText.isEmpty()) {
continue;
}

if (first)
first = false;
else
result.append(" ");

result.append(childText);
}

return result.toString();
}

我使用以下两个 XML 输入对其进行了测试,因为您的 XML 缺少结束符 </property>标签。

这是第一个(我添加了额外的元素,以表明找不到它们):

  <rootNode>
<property regex=".*" xpath=".*">
<value>
127.0.0.1
</value>
<anythingElse>Text here</anythingElse>
</property>
<anythingElse>Text here</anythingElse>
<property regex=".*" xpath=".*">
<value>
val <![CDATA[
<Valve className="org.tomcat.AccessLogValve" exclude="PASSWORD,pwd,pWord,ticket" enabled="true" serviceName="zohocrm" logDir="../logs" fileName="access" format="URI,&quot;PARAM&quot;,&quot;REFERRER&quot;,TIME_TAKEN,BYTES_OUT,STATUS,TIMESTAMP,METHOD,SESSION_ID,REMOTE_IP,&quot;INTERNAL_IP&quot;,&quot;USER_AGENT&quot;,PROTOCOL,SERVER_NAME,SERVER_PORT,BYTES_IN,ZUID,TICKET_DIGEST,THREAD_ID,REQ_ID"/>
]]> test
</value>
</property>
</rootNode>

第二个有嵌套的属性元素(我在末尾添加了缺少的元素):

  <property regex=".*" xpath=".*">
<value>
127.0.0.1
</value>
<property regex=".*" xpath=".*">
<value>
val <![CDATA[
<Valve className="org.tomcat.AccessLogValve" exclude="PASSWORD,pwd,pWord,ticket" enabled="true" serviceName="zohocrm" logDir="../logs" fileName="access" format="URI,&quot;PARAM&quot;,&quot;REFERRER&quot;,TIME_TAKEN,BYTES_OUT,STATUS,TIMESTAMP,METHOD,SESSION_ID,REMOTE_IP,&quot;INTERNAL_IP&quot;,&quot;USER_AGENT&quot;,PROTOCOL,SERVER_NAME,SERVER_PORT,BYTES_IN,ZUID,TICKET_DIGEST,THREAD_ID,REQ_ID"/>
]]> test
</value>
</property>
</property>

关于java - XML 将节点值解析为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12550542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com