如何通过java获取Xml的本地属性值

时间:2015-04-16 03:47:49

标签: java xml

我尝试了一些方案,但无法通过java

获取以下xml的属性值
enter code here

    <?xml version="1.0" encoding="utf-8"?>
    <Rules>
    <Rule ID="1" Name="Ms 45 MD -&gt; BS 1 ON @ 300 secs" Valid="1">
            <Triggers Count="1">
            <Trigger ID="1" TriggerType="Device" DeviceID="4" DeviceIndex="1" GroupingType="AND" Condition="eq" Validation="true" Duration="2147483647">true</Trigger>
            </Triggers>
            <Results Count="1">
                    <Result ID="1" ResultType="DeviceResult" DeviceID="1" DeviceIndex="1" PreDelay="300" Validation="true">true</Result>
            </Results>
    </Rule>
    </Rules>

我需要以下属性的值 - 触发器计数,触发器ID,触发器类型,DeviceID和触发器标签之间的数据 - 结果计数,结果ID,ResultType,DeviceID,preDelay和循环中结果标记之间的数据

1 个答案:

答案 0 :(得分:2)

以下是打印“计数”值的方法。

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse("put_the_path_to_your_file_here");
doc.getDocumentElement().normalize();

NodeList rules = doc.getDocumentElement().getElementsByTagName("Rule");
for (int i = 0; i < rules.getLength(); ++i) {
  Element rule = (Element) rules.item(i);
  Element triggers = (Element) rule.getElementsByTagName("Triggers").item(0);
  int count = Integer.parseInt(triggers.getAttribute("Count"));
  System.out.println("Count=" + count);
}

您需要在第3行的.parse调用中指定文件的路径。

另请注意,要编译此代码,您必须导入以下内容:

import java.io.File;
import javax.xml.parsers.*;
import org.w3c.dom.*;