gpt4 book ai didi

Java - XML读取根元素值

转载 作者:行者123 更新时间:2023-12-01 12:19:34 29 4
gpt4 key购买 nike

<?xml version="1.0" encoding="UTF-8"?>
<JDF DescriptiveName="DescriptiveName" ID="n0001" JobID="1101-CCC-0" JobPartID="1" ProjectID="">
<Comment Name="Materialnummer">XXXXXXX</Comment>
<NodeInfo LastEnd="2014-03-12T18:00:00+01:00">
<EmployeeRef rRef="EMPCSR"/>
</NodeInfo>
<CustomerInfo CustomerID="1740">
</CustomerInfo>
<ResourcePool>
</ResourcePool>
<ResourceLinkPool>
</ResourceLinkPool>
<JDF Category="FinalImaging" ID="n0002" Status="Waiting" Type="ProcessGroup" Types="XXX">
<ResourcePool>
</ResourcePool>
<ResourceLinkPool>
</ResourceLinkPool>
</JDF>
<JDF ID="n0002" Status="Waiting" Type="ProcessGroup" Types="PrePressPreparation">
<ResourcePool>
</ResourcePool>
<ResourceLinkPool>
</ResourceLinkPool>
</JDF>
</JDF>

如何获取根元素值。对于此示例,我想要获取 DescriptiveNameIDJobIDProjectID。我设法读取其他值,但卡在根元素中。请指教。已编辑

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
//System.out.println("*************************");
String expression = "/JDF";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);

最佳答案

这里是一个示例:

import java.io.File;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class Main {
public static void main(String[] argv) throws Exception{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);

factory.setExpandEntityReferences(false);

Document doc = factory.newDocumentBuilder().parse(new File("filename"));

Element root = null;

NodeList list = doc.getChildNodes();
for (int i = 0; i < list.getLength(); i++) {
if (list.item(i) instanceof Element) {
root = (Element) list.item(i);
break;
}
}
root = doc.getDocumentElement();
}
}

您可以从root对象获取属性

关于Java - XML读取根元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26796869/

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