gpt4 book ai didi

Java DOM XML 解析

转载 作者:行者123 更新时间:2023-12-04 06:05:33 24 4
gpt4 key购买 nike

所以我有一个格式为的 XML 文件:

<projectlist>
<project>
<name>test</name>
<type>deploy</type>
<environment>dev</environment>
<server>test01</server>
<server>test02</server>
<server>test03</server>
</project>
</projectlist>

我试图解析这个文件并构建一个对象,我可以用不同的服务器的名称和单选按钮组填充 JListBox,但是每个项目由不同数量的服务器组成。如何迭代节点/子节点以使用多个服务器构建对象。这是我从网站借来的代码片段和我的一些代码片段,我不太擅长编码,所以请耐心等待。当我调试时,它开始解析和构建对象,但是一旦它到达服务器名称,它就会打印一个空指针异常,所以我做的事情完全错误。
public class XMLParser {
public Project currentProject = new Project();

public void parseXML() throws Exception {

try {
File file = new File("c:\\projectlist.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(file);
doc.getDocumentElement().normalize();

NodeList nList = doc.getElementsByTagName("project");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;

currentProject.SetAppName(getTagValue("name", eElement));
currentProject.SetType(getTagValue("type", eElement));
currentProject.SetEnvironment(getTagValue("environment", eElement));
currentProject.SetServerName(getTagValue("server", eElement));



}
}




} catch (Exception e) {
e.printStackTrace();
}

}
private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

Node nValue = (Node) nlList.item(0);

return nValue.getNodeValue();
}


public final class Project {
protected String AppName = null;
protected String Type = null;
protected List<String> ServerNames = null;
protected String Environment = null;

public void SetAppName(String AppName) {
this.AppName = AppName;
}

public void SetType(String DeployType) {
this.Type = DeployType;
}

public void SetServerName(String ServerName) {
this.ServerNames.add(ServerName);
}

public void SetEnvironment(String Environment) {
this.Environment = Environment;
}

public String getAppName() {
return AppName;
}

public String getType() {
return Type;
}

public List<String> getServerName() {
return ServerNames;
}

public String getEnvironment() {
return Environment;
}


}

最佳答案

您的异常是因为您没有在 Project 类中初始化 ServerNames 引起的。尝试按如下方式初始化并重新运行:
final protected List<String> ServerNames = new ArrayList<String>();

关于Java DOM XML 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8404322/

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