需要使用具有相同名称的子节点迭代xml

时间:2016-06-22 16:30:06

标签: java xml nodes

我有xml

<CommonTestData>
<GiftCards> 
  <GiftCard>
      <cardnumber>7777016774730834</cardnumber>
      <number>1815</number>
  </GiftCard>
  <GiftCard>
      <cardnumber>7777016774687937</cardnumber>
      <number>6256</number>
  </GiftCard>
</GiftCards>

我必须迭代这些xml并读取值并输入Selenium Web应用程序并检查礼品卡应用量是否大于零。 If the amount applied is zero then try another card . If the amount applied is greater than zero then break the loop

我的代码看起来像

for (int i=0;i<xmlvalue.getNodeCount("GiftCard", "CommonTestData.xml");i++){
            //giftcardaccordian.click();
            giftcardnumber.sendKeys(xmlvalue.getValue("cardnumber"+i, "GiftCard", "CommonTestData.xml")); // I need code for getvalue function so that i can iterate through 
            giftcardpin.sendKeys(xmlvalue.getValue("cardnumber"+i, "GiftCard", "CommonTestData.xml"));

            giftcardapplybutton.click();
            try{
                if(appliedgiftcardamount.getText()!="$0"){
                    break;
                }
            }catch (Exception e ){
                Assert.fail("Cannot apply reward certicate");
            }
        }

我需要实现Getvalue,以便我可以迭代。现在我的实现类似于

public String getValue(String csstagname, String Elementname, String xmlfilename) {
    String eElement1;

    try {
      String path = "config/XML/" + xmlfilename;
      File fXmlFile = new File(path);
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(fXmlFile);
      doc.getDocumentElement().normalize();
      NodeList nList = doc.getElementsByTagName(Elementname);

      for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
          eElement1 = csstagname;
          Element eElement2 = (Element) nNode;

          value = (getTagValue(eElement1, eElement2));

        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {

      return (value);
    }
  }

1 个答案:

答案 0 :(得分:0)

您正在做的事情是可能的,但它不符合XML的精神。你控制XML文件吗?更改格式,以便卡号和号码有自己的总体标记将它们绑定在一起:

<CommonTestData>
    <GiftCards> 
      <GiftCard>
          <cardnumber>7777016774730834</cardnumber>
          <number>1815</number>
      </GiftCard>
      <GiftCard>
          <cardnumber>7777016774687937</cardnumber>
          <number>6256</number>
      </GiftCard>
    </GiftCards>
</CommonTestData>

如果您不控制格式,请提取标有cardnumber的所有节点,所有标记为number的节点,然后访问具有相同索引的两个阵列。