Parsing XML attributes in java

2019-07-15 21:14发布

问题:

I have an xml similar to this

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

I want to parse this and store to Strings Like VendorId, AuthApplId etc. I got ApplicationID parsed with getElementsByTagName("ApplicationID") if it was <ApplicationID value="somevalue"/> then I can use getAttribute("value") method. but in the above mentioned situation what should I do?

回答1:

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       
}