gpt4 book ai didi

java - 减少 XML 文档上的重复循环代码

转载 作者:行者123 更新时间:2023-12-02 06:40:36 26 4
gpt4 key购买 nike

我有以下代码部分:

第一种方法:

public ArrayList<String> getTestFilesForOrderNumber(Integer testStepOrderNumber, Integer testOrderNumber,
String version)
{
NodeList list = documentTest.getElementsByTagName(XmlElements.TESTSTEPS);
ArrayList<String> files = new ArrayList<>();
for (int i = 0; i < list.getLength(); i++)
{
Element e = (Element) list.item(i);
if (e.getAttribute(XmlAttributes.VERSION).equalsIgnoreCase(version))
{
list = e.getElementsByTagName(XmlElements.TESTSTEP);
for (int l = 0; l < list.getLength(); l++)
{
e = (Element) list.item(l);
if (e.getAttribute(XmlAttributes.ORDER_NUMBER).equals(testStepOrderNumber.toString()))
{
NodeList testsList = e.getElementsByTagName(XmlElements.TEST);
for (int j = 0; j < testsList.getLength(); j++)
{
Element e2 = (Element) testsList.item(j);
if (e2.getAttribute(XmlAttributes.ORDER_NUMBER).equals(testOrderNumber.toString()))
{
NodeList fileList = e2.getElementsByTagName(XmlElements.FILE);
for (int k = 0; k < fileList.getLength(); k++)
{
Element e3 = (Element) fileList.item(k);
if (e3.getParentNode().getNodeName().equals(XmlElements.FILES))
{
files.add(e3.getFirstChild().getNodeValue());
}
}
}
}
}
}
}
}

return files;
}

第二种方法:

public String getTestDescription(String langCode, Integer testStepOrderNumber, Integer testOrderNumber, String version)
{
NodeList list = documentTest.getElementsByTagName(XmlElements.TESTSTEPS);
for (int i = 0; i < list.getLength(); i++)
{
Element e = (Element) list.item(i);
if (e.getAttribute(XmlAttributes.VERSION).equalsIgnoreCase(version))
{
list = e.getElementsByTagName(XmlElements.TESTSTEP);
for (int l = 0; l < list.getLength(); l++)
{
e = (Element) list.item(l);
if (e.getAttribute(XmlAttributes.ORDER_NUMBER).equals(testStepOrderNumber.toString()))
{
NodeList testsList = e.getElementsByTagName(XmlElements.TEST);
for (int j = 0; j < testsList.getLength(); j++)
{
Element e2 = (Element) testsList.item(j);
if (e2.getAttribute(XmlAttributes.ORDER_NUMBER).equals(testOrderNumber.toString()))
{
NodeList testList = e2.getElementsByTagName(langCode.toUpperCase());
for (int k = 0; k < testList.getLength(); k++)
{
Element e3 = (Element) testList.item(k);
if (e3.getParentNode().getNodeName().equals(XmlElements.DESCRIPTION))
{
return testList.item(k).getFirstChild().getNodeValue();
}
}
}
}
}
}
}
}

return "ERROR_NO_TEST_DESC";
}

现在,如您所见,第一个 for 循环完全相同,但方法返回值和方法参数不同。现在我不知道如何减少这些重复的代码。

提前谢谢您。

最佳答案

看来使用 XPath 可能会有所帮助。请查看tutorial at w3schools和一些usage examples in java

关于java - 减少 XML 文档上的重复循环代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19175711/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com