【问题标题】:Need to iterate an xml with child nodes with same name需要使用具有相同名称的子节点迭代 xml
【发布时间】:2016-10-24 17:30:17
【问题描述】:

我有一个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);
    }
  }

【问题讨论】:

  • 您的问题与 Selenium 没有任何关系。您应该删除该标签。

标签: java xml nodes


【解决方案1】:

您正在做的事情是可能的,但这不符合 XML 的精神。您是否控制 XML 文件?更改格式,使卡的 nnumber 和 number 有自己的总体标签将它们绑定在一起:

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

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

【讨论】:

  • 是的,我可以更改 XML 格式。是的,我会改变这个,看起来不错
猜你喜欢
  • 2020-10-27
  • 2013-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多