gpt4 book ai didi

java - 解析 XML 时将子节点与控制值进行比较

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:14 25 4
gpt4 key购买 nike

我有一个像这样组织的 XML 文件,每个节点下的项目始终按字母顺序排列:

<xml>
<node id="2">
<jack>Jack wrote this.</jack>
<john>John wrote this.</john>
</node>

<node id="4">
<jack>Jack wrote this.</jack>
<jill>Jill wrote this.</jill>
</node>

<node id="9">
<jack>Jack wrote this.</jack>
<james>James wrote this.</james>
<jill>Jill wrote this.</jill>
<john>John wrote this.</john>
</node>
</xml>

正如您所看到的,并非所有名称都位于每个节点下。例如,在<node id="4">中、约翰和詹姆斯没有写任何东西。对于上面的示例,我希望我的程序返回如下内容:

James did not write 2, 4
Jill did not write 2
John did not write 4

我需要跟踪谁没有写什么。我目前正在像这样解析文档:

private static String getTagValue(final Element element)
{
String theId="";
if (element.getTagName().startsWith("node")){

theId = element.getAttribute("id");
return theId;
}
return theId;
}


private static void readXML(String fileName){

for (int index = 0; index < nodeList.getLength(); index++){

Node node = nodeList.item(index);
Element element = (Element) node;

if (node.getNodeType() == Node.ELEMENT_NODE){

// This prints the node id
if(getTagValue(element)!=""){
System.out.println(getTagValue(element)+" = I am the node id number!");
}

// This prints the name
else{
System.out.println(element.getTagName()+" = I am the name!");
}
}
}
}

我想做的是以某种方式将每个节点下的元素与包含所有名称的“控制”列表进行比较,如果它不包含名称,则返回名称及其父节点。

实际上,我正在处理的 XML 要大得多,因此性能很重要,但概念是相同的。任何帮助都会很棒。

最佳答案

维持两套。一个是所有名称的主集 ( A )。第二个是您在每次迭代期间建立的一组回答问题的人员 ( B )。那么没有回答的人就是 A - B ,您可以使用 Collection#removeAll(Collection c) 来做到这一点:

A.removeAll(B);

您提到您想在一行中打印出一个人没有回答的答案。为此,您可以维护一个映射 ( Map<String, List<Integer>> ),将某人的姓名映射到他们未回答的问题编号列表中。您可以通过检查 A.removeAll(B) 的结果来做到这一点在一次迭代结束时。

因此,一旦完成所有节点的循环,您最终会得到一个 map ,其中为您提供与他们未回答的问题列表相关的每个名称。然后,您可以迭代此 map 并打印出您需要的内容。

关于java - 解析 XML 时将子节点与控制值进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12808405/

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