我需要获取Device
ID
、DeviceType
、第一个LastKnownValue
标签的数据。 XML 是
<?xml version="1.0" encoding="utf-8"?>
<DeviceList Devid="" Count="35">
<Device ID="01">
<Name>@@@@@</Name>
<DeviceType>Me</DeviceType>
<ValueVariables Count="3">
<LastKnownValue Index="1" EndPoint="1" Name="STATE" Type="Bool">false</LastKnownValue>
<LastKnownValue Index="2" EndPoint="1" Name="LOW BATTERY" Type="Bool">0</LastKnownValue>
<LastKnownValue Index="3" EndPoint="1" Name="TAMPER" Type="Bool">false</LastKnownValue>
</ValueVariables>
</Device>
</DeviceList>
我尝试了以下代码,但无法获取属性的值。
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse("xml path");
doc.getDocumentElement().normalize();
NodeList devicelist = doc.getDocumentElement().getElementsByTagName("Device");
System.out.println(devicelist.getLength());
for (int i = 0; i < devicelist.getLength(); ++i)
{
Element rule = (Element) devicelist.item(i);
//Device ID
String ruleid = rule.getAttribute("ID");
System.out.println(ruleid);
}
最佳答案
我建议使用 XPath直接从 XML 中获取节点值,而不是遍历并获取所需的节点。
如果 Device
节点只出现一次,那么您可以使用下面的 XPath 表达式来获取数据。
XPath
获取 Device ID
是 - //*/Device/@ID
或 /DeviceList/Device/@ID
XPath
获取 DeviceType
是 - //*/DeviceType
或 /DeviceList/Device/DeviceType
XPath
获取第一个 LastKnownValue
- (//*/LastKnownValue)[1]
关于java - 如何获取xml的内部属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29766946/