在java中解析XML属性

时间:2012-06-28 08:10:27

标签: java xml dom xml-parsing

我有一个与此类似的xml

<Applications>
  <ApplicationID>
    <VendorId value="0" />
    <AuthApplId value="4" />
    <AcctApplId value="0" />
  </ApplicationID>
  <ApplicationID>
    <VendorId value="193" />
    <AuthApplId value="0" />
    <AcctApplId value="19302" />
  </ApplicationID>
</Applications>

我想解析这个并存储到Strings Like VendorId,AuthApplId等。如果是getElementsByTagName("ApplicationID"),我使用<ApplicationID value="somevalue"/>解析了ApplicationID,然后我可以使用getAttribute("value")方法。但在上述情况下我该怎么办?

1 个答案:

答案 0 :(得分:2)

NodeList applicationIDNodes = getElementsByTagName("ApplicationID");
for (int i = 0; i < applicationIDNodes.length; i++) {
   Node applicationIDNode = applciationIdNodes.getItem(i);
   NodeList applicationIdChildren = applicationIdNode.getChildren();

   String vendorId = applicationIdChildren.getItem(0).getAttribute("value").value();
   String authAppliId = applicationIdChildren.getItem(1).getAttribute("value").value();
   String actApplID = applicationIdChildren.getItem(2).getAttribute("value").value();

   // do whathever you want with vendorId, authAppliId, actApplID       
}