gpt4 book ai didi

java - dom4j.Node 迭代元素映射

转载 作者:行者123 更新时间:2023-12-01 12:35:20 25 4
gpt4 key购买 nike

dom4j.Node 处理 xml 文件,我遇到了与 Map 类似的结构的问题。我遵循了文档结构:

<Party>
<Identifier>1113ddbed7b54890abfe2f8c9754d689</Identifier>
<Address>
</Address>
<Contact>
<ContactInfo>
<Key>IPS</Key>
<Value>null</Value>
<Key>keyTwo</Key>
<Value>1234</Value>
(...)
</ContactInfo>
</Contact>
</Party>

我的目标是获取 keyTwo 元素的值。如何以灵活、非硬编码的方式获取这些元素?

我的第一个想法是这样的:

    //parent node is father element
Node parentDocument = parentNode.selectSingleNode("ContactInfo");
List<Node> nodesKeys = contactNode.selectNodes("Key");
List<Node> nodesValues = contactNode.selectNodes("Value");

for(int i=0; i<nodesKeys.size(); i++){

if(nodesKeys.get(i).selectSingleNode("Key").equals("keyTwo")){
return nodesValues.get(i);
}
}

但我不确定这是否是一个好的方法,特别是键和值列表的排序是否正确。

最佳答案

这是一个完整的工作示例:

Maven:PoM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sofrecom</groupId>
<artifactId>XmlProcessing</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
</project>

Java 主要:

package xmlprocessing;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

/**
*
* @author z.benrhouma
*/
public class Main {

public static void main(String... args) {

try {
Document document = parse("src/main/resources/file.xml");
Node node = document.selectSingleNode( "//Party/Contact/ContactInfo/Key[text()='keyTwo']/following-sibling::Value[1]");
System.out.println(node.getText());
} catch (Exception e) {
e.printStackTrace();
}


}
public static Document parse(String path) throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(path);
return document;
}
}

XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<Party>
<Identifier>1113ddbed7b54890abfe2f8c9754d689</Identifier>
<Address>
</Address>
<Contact>
<ContactInfo>
<Key>IPS</Key>
<Value>null</Value>
<Key>keyTwo</Key>
<Value>1234</Value>

</ContactInfo>
</Contact>
</Party>

关于java - dom4j.Node 迭代元素映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25646113/

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