使用Java提取XML的所有重复元素

问题描述 投票:0回答:1

我的XML如下所示,我需要在其中提取多个ID元素输出xml:-

<?xml version="1.0" encoding="utf-8"?>
<Stock>
    <PIdentification>
    <CatalogVersion></CatalogVersion>
    <AccountID></AccountID>
    <CustomerId></CustomerId>
    </ProviderIdentification>
    <Product>
        <ArticleName>Monitors</ArticleName>
        <BaseUnit></BaseUnit>
        <Notes></Notes>
        <ID>11f13e2e-ae97-45b5-a9a9-23fa7f6bb767</ID>
        <ID>b22834c0-a570-4e6b-97c3-5067a14d118d</ID>
        <ID>ed458593-5e1a-4dc1-94f0-a66eeef2dd79</ID>
        <ID>d25584a9-1db2-48cf-9a70-9b81e5a7e7f2</ID>
    </Product>
</Stock>

我已经使用“ Nodelist”提取“ ID”,但是我只得到一个元素而不是全部4,下面是代码的一部分:-

{   
    Node IDNode = element.getElementsByTagName("ID").item(0);
    IDXml = toStringXml(IDNode , true);
}

我无法重申要获得所有ID的外观,请让我知道如何获取所有ID,不胜感激。

    private static String toStringXml(Node elt, boolean xmlDeclaration) 
    throws TransformerException {
     TransformerFactory transformerFactory = TransformerFactory
        .newInstance();
    Transformer transformer = transformerFactory.newTransformer();

    if(xmlDeclaration)
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    DOMSource source = new DOMSource(elt);
    StreamResult result = new StreamResult(new StringWriter());
    transformer.transform(source, result);

    return result.getWriter().toString();
    }
java xml xml-parsing nodes nodelist
1个回答
0
投票
File xmlFile = new File("src/main/resources/example.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document element = dBuilder.parse(xmlFile); NodeList list = element.getElementsByTagName("ID"); for (int i = 0; i < list.getLength(); i++){ Node specificIDNode = list.item(i); System.out.println(specificIDNode.getTextContent()); }
© www.soinside.com 2019 - 2024. All rights reserved.