从JAVA中的XML文件打印子元素时无效的答案

时间:2014-09-23 09:48:56

标签: java xml

我试图使用JAVA从XML文件中获取父元素的子元素数。以下是我正在使用的代码:

File fXmlFile = new File("SearchPromotions.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

NodeList l = doc.getElementsByTagName("TestCase");
Node parentNode = l.item(0);
int count = parentNode.getChildNodes().getLength();

System.out.println(count);

这是XML文件:

<TestCase>
    <SelectedDataTableNames name="SearchData"> </SelectedDataTableNames>

    <Open page="hsbc"  ms="5000"  />
    <Click object="hsbc.Personal_Link"  />
    <Click object="hsbc.CreditCard_tab"  />
    <Call businessComponent="Global.Verify_Search">
       <Param name="HotelName_Param" value="@SearchData_link" />
    </Call>
    <CheckElementPresent object="hsbc.Img_Hotel_logo"  Identifire="Hotel_Name_PARAM:@SearchData_ResultHotelName"  fail="true"  customErrorMessage="Searched hotel name is not present in the page."  />
</TestCase>

我面临的问题是它打印错误的值。打印的值是13.但是正如您所看到的,父元素只有6个子元素&#34; TestCase&#34;。我哪里做错了。请帮忙

3 个答案:

答案 0 :(得分:1)

public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        String fileContent = readFile("SearchPromotions.xml");// Read trimmed file
        InputStream in = new ByteArrayInputStream(fileContent.getBytes("UTF-8"));// Create stream to pass it to parser()
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(in);

        NodeList l = doc.getElementsByTagName("TestCase");
        Node parentNode = l.item(0);
        int count = parentNode.getChildNodes().getLength();

        System.out.println(count);
    }

    private static String readFile(String pathname) throws IOException {
        File file = new File(pathname);
        StringBuilder fileContents = new StringBuilder((int) file.length());
        Scanner scanner = new Scanner(file);
        try {
            while (scanner.hasNextLine()) {
                fileContents.append(scanner.nextLine().trim()); // Trim the whitespace. This resuls in TEXT_NODE.
            }
            return fileContents.toString();
        } finally {
            scanner.close();
        }
    }

XML中有一些空格字符会导致额外的节点。试试上面的解决方案希望它有所帮助。

答案 1 :(得分:1)

节点的子节点包括空格文本节点以及子元素节点。

为什么不用XPath做到这一点 - 它不那么麻烦了!

使用Saxon和XPath 2.0,它将是

Processor p = new Processor(false);
XdmNode doc = p.newDocumentBuilder().build(
    new StreamSource(new File("searchPromotions.xml")));
XdmItem result = p.newXPathCompiler().evaluateSingle("/TestCase/count(*)", doc);
System.out.println(result.getStringValue());

答案 2 :(得分:0)

找到问题的答案。有用。我遇到的问题是ELEMENT_NODE。我们必须过滤ELEMENT_NODE。这是工作代码。感谢所有帮助过那里的人。

File fXmlFile = new File("SearchPromotions.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();

Element docEle = doc.getDocumentElement();
NodeList nl = docEle.getChildNodes();
if (nl != null && nl.getLength() > 0) {
      for (int i = 0; i < nl.getLength(); i++) {
           if (nl.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element el = (Element) nl.item(i);
                System.out.println(el);
            }
      }
}