gpt4 book ai didi

java - 如何在java中使用dom解析器按属性获取元素

转载 作者:数据小太阳 更新时间:2023-10-29 02:23:54 25 4
gpt4 key购买 nike

我不知道如何通过属性获取元素。我尝试了下面的方法,但出现错误,因为 item(1) 可能会随着循环的进行而改变。一些字段标签可能会被剥离。所以位置可能会改变。我想得到:

<field name="Test/Content/Modified">Thu Jun 01 13:11:43 2014</field>

XML:

 <assets>
<document path="some/path/1">
<metadata>
<field name="Test/Content/Date">2013-12-20</field>
<field name="Test/Content/Modified">Thu Jun 01 13:11:43 2014</field>
<field name="Test/Locale">en_US</field>
<field name="Test/Content/SubSolution"></field>
</metadata>
</document>
<document path="some/path/2">
<metadata>
<field name="Test/Content/Date">2013-12-20</field>
<field name="Test/Locale">en_US</field>
<field name="Test/Content/Modified">Thu Jun 01 13:11:43 2014</field>
<field name="Test/Content/SubSolution"></field>
</metadata>
</document>
<assets>

java部分代码:

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse("E:\\example.xml");

List<String> list = new ArrayList<>();

NodeList nList = doc.getElementsByTagName("document");
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
Date date = new Date(eElement.getElementsByTagName("field").item(1).getTextContent());
System.out.println(date);
Date date1 = new Date(2014 - 1900, 06 - 1, 04);
if (date.compareTo(date1) == 1) {
list.add(eElement.getAttribute("path").trim());
}
}
}

最佳答案

您需要遍历 field 节点并检查匹配的属性值:

    NodeList nList = doc.getElementsByTagName("document");
for (int i = 0; i < nList.getLength(); i++) {
Node nNode = nList.item(i);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
NodeList fieldNodes = eElement.getElementsByTagName("field");
for(int j = 0; j < fieldNodes.getLength(); j++) {
Node fieldNode = fieldNodes.item(j);
NamedNodeMap attributes = fieldNode.getAttributes();
Node attr = attributes.getNamedItem("name");
if(attr != null) {
if(attr.getTextContent().equals("Test/Content/Modified")) {
Date date = new Date(fieldNode.getTextContent());
System.out.println(date);
Date date1 = new Date(2014 - 1900, 06 - 1, 04);
if (date.compareTo(date1) == 1) {
list.add(eElement.getAttribute("path").trim());
}
}
}
}
}
}

关于java - 如何在java中使用dom解析器按属性获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24220652/

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