JAVA循环遍历Nodelist的子元素

huangapple go评论72阅读模式
英文:

JAVA loop through children of Nodelist

问题

import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class SolutionXML2XmlFormat {
    public static String ankomstDato_value;
    public static String[] planlagtAntallPerUndergruppe_antall_value = new String[6];
    public static String[] planlagtAntallPerUndergruppe_kode_value = new String[6];

    public void Xml2JavaObject(String FromThis) {
        try {
            File file = new File(FromThis);
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(file);
            document.getDocumentElement().normalize();
            
            String ankomstDato = document.getElementsByTagName("ankomstDato").item(0).getTextContent();
            ankomstDato_value = ankomstDato;

            NodeList planlagtAntallPerUndergruppe = document.getElementsByTagName("planlagtAntallPerUndergruppe");
            for (int temp = 0; temp < planlagtAntallPerUndergruppe.getLength(); temp++) {
                Node nNode = planlagtAntallPerUndergruppe.item(temp);

                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;
                    String element18 = eElement.getElementsByTagName("antall").item(0).getTextContent();
                    planlagtAntallPerUndergruppe_antall_value[temp] = element18;

                    String element19 = eElement.getElementsByTagName("kode").item(0).getTextContent();
                    planlagtAntallPerUndergruppe_kode_value[temp] = element19;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Write2XMLfile();
    }

    public void Write2XMLfile() {
        XPathFactory xpathFact = XPathFactory.newInstance();
        XPath xpath = xpathFact.newXPath();

        try {
            String filepath = "E:/utils/Tothis.xml";
            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(filepath);

            Node ankomstDato = (Node) xpath.evaluate("(/map/string[@key='ankomstDato'])[1]", doc, XPathConstants.NODE);
            ankomstDato.setTextContent(ankomstDato_value);

            Node planlagtAntallPerUndergruppe = (Node) xpath.evaluate("/map/array[@key='planlagtAntallPerUndergruppe']/*", doc, XPathConstants.NODE);
            if (null != planlagtAntallPerUndergruppe) {
                NodeList nodeList = planlagtAntallPerUndergruppe.getChildNodes();
                for (int i = 0; null != nodeList && i < nodeList.getLength(); i++) {
                    Node nod = nodeList.item(i);
                    if (nod.getNodeType() == Node.ELEMENT_NODE) {
                        NodeList arrayElements_18 = (NodeList) xpath.evaluate("/map/array[@key='planlagtAntallPerUndergruppe']/*", doc, XPathConstants.NODESET);
                        for (int j = 0; j < arrayElements_18.getLength(); j++) {
                            Node antall = (Node) xpath.evaluate("(/map/array/map/number[@key='antall'])[1]", doc, XPathConstants.NODE);
                            antall.setTextContent(planlagtAntallPerUndergruppe_antall_value[j]);

                            Node kode = (Node) xpath.evaluate("(/map/array/map/string[@key='kode'])[1]", doc, XPathConstants.NODE);
                            kode.setTextContent(planlagtAntallPerUndergruppe_kode_value[j]);
                        }
                    }
                }
            }

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(new File(filepath));
            transformer.transform(source, result);
            System.out.println("Done Updating The Api_XML_Format.xml");
        } catch (ParserConfigurationException | TransformerException | IOException | SAXException | XPathExpressionException e) {
            e.printStackTrace();
        }
    }
}

Note: The provided code seems to have some issues, and it's not entirely clear what you're trying to achieve. The translation includes the code as is, but please review it and make sure it fits your requirements.

英文:

I have an XML file call it (FromThis.xml) with sample data see below:

I want to read from the file(FromThis.xml) , store the values in variable then use those variable while creating a second XML file(ToThis.xml).

Brief description of my scenario[ I will read values from XML file(FromThis.xml) first and store them in a variables. Then I will use the variables to update the second xml file which is (ToThis.xml .I later use this xml to create some JSON file in some specified format.) I have been working with this but later we need to send array of elements in (FromThis.xml). From my code below i can only get the first array element but i want to loop through the elements, store them and use it to create the second xml (ToThis.xml)

(FromThis.xml)

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;no&quot;?&gt;
&lt;Root&gt;
&lt;ankomstDato&gt;2020-08-20&lt;/ankomstDato&gt;
&lt;planlagtAntallPerUndergruppe&gt;
&lt;element&gt;
&lt;antall&gt;67&lt;/antall&gt;
&lt;kode&gt;SLAKTEGRIS&lt;/kode&gt;
&lt;/element&gt;
&lt;element&gt;
&lt;antall&gt;4&lt;/antall&gt;
&lt;kode&gt;UNGSAU&lt;/kode&gt;
&lt;/element&gt;
&lt;/planlagtAntallPerUndergruppe&gt;
&lt;/Root&gt;

(ToThis.xml) Below xml is what i currently get.

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;map xmlns=&quot;http://www.w3.org/2005/xpath-functions&quot;&gt;
&lt;string key=&quot;ankomstDato&quot;&gt;2020-08-20&lt;/string&gt;
&lt;array key=&quot;planlagtAntallPerUndergruppe&quot;&gt;
&lt;map&gt;
&lt;number key=&quot;antall&quot;&gt;67&lt;/number&gt;
&lt;string key=&quot;kode&quot;&gt;SLAKTEGRIS&lt;/string&gt;
&lt;/map&gt; 
&lt;/array&gt;   
&lt;/map&gt;

What i would like to get as the result is

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;map xmlns=&quot;http://www.w3.org/2005/xpath-functions&quot;&gt;
&lt;string key=&quot;ankomstDato&quot;&gt;2020-08-20&lt;/string&gt;
&lt;array key=&quot;planlagtAntallPerUndergruppe&quot;&gt;
&lt;map&gt;
&lt;number key=&quot;antall&quot;&gt;67&lt;/number&gt;
&lt;string key=&quot;kode&quot;&gt;SLAKTEGRIS&lt;/string&gt;
&lt;/map&gt; 
&lt;map&gt;
&lt;number key=&quot;antall&quot;&gt;4&lt;/number&gt;
&lt;string key=&quot;kode&quot;&gt;UNGSAU&lt;/string&gt;
&lt;/map&gt;
&lt;/array&gt;   
&lt;/map&gt;

Below is my Code

    import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.w3c.dom.Element;
//** */
public class SolutionXML2XmlFormat {
//Create Public Variables to store data
//**
public static String ankomstDato_value; //1
public static String[] planlagtAntallPerUndergruppe_antall_value = new String[6]; //
public static String[] planlagtAntallPerUndergruppe_kode_value = new String[6]; //
//+++
public void Xml2JavaObject(String FromThis){
//read the xml(TheXMLPath) and store values in variables
// Boolean and numbers should be having values for string use &quot; &quot; if empty
try {
File file = new File(FromThis);
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
document.getDocumentElement().normalize();
System.out.println(&quot;Root element :&quot; + document.getDocumentElement().getNodeName());
System.out.println(&quot;------------------------ \n&quot;);
//1 . ankomstDato
String ankomstDato = document.getElementsByTagName(&quot;ankomstDato&quot;).item(0).getTextContent();
ankomstDato_value = ankomstDato;
//end ankomstDato
NodeList planlagtAntallPerUndergruppe= document.getElementsByTagName(&quot;planlagtAntallPerUndergruppe&quot;);
for (int temp = 0; temp &lt; planlagtAntallPerUndergruppe.getLength(); temp++) {                
Node nNode = planlagtAntallPerUndergruppe.item(temp);
System.out.println(&quot;\n Current Elements :&quot; + planlagtAntallPerUndergruppe.getLength());
System.out.println(&quot;\n No. of  Element :&quot; + temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String element18 = eElement.getElementsByTagName(&quot;antall&quot;).item(0).getTextContent();                    
planlagtAntallPerUndergruppe_antall_value[temp] = element18;  
String element19 = eElement.getElementsByTagName(&quot;kode&quot;).item(0).getTextContent();                    
planlagtAntallPerUndergruppe_kode_value[temp] = element19;               
} 
} 
} catch (Exception e) {
e.printStackTrace();
}
//Call method to write values
Write2XMLfile();
}
public void Write2XMLfile(){
XPathFactory xpathFact = XPathFactory.newInstance();
XPath xpath = xpathFact.newXPath();
try {
//
String filepath = &quot;E:/utils/Tothis.xml&quot;;
//
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
// 1. ankomstDato
Node ankomstDato = (Node) xpath.evaluate(&quot;(/map/string[@key=&#39;ankomstDato&#39;])[1]&quot;, doc, XPathConstants.NODE);
ankomstDato.setTextContent(ankomstDato_value );
// End ankomstDato
//2.  planlagtAntallPerUndergruppe **************************
System.out.println(&quot;\n This is second&quot; );
Node planlagtAntallPerUndergruppe = (Node) xpath.evaluate(&quot;/map/array[@key=&#39;planlagtAntallPerUndergruppe&#39;]/*&quot;, doc, XPathConstants.NODE);
if(null != planlagtAntallPerUndergruppe) {
NodeList nodeList = planlagtAntallPerUndergruppe.getChildNodes();
for (int i = 0;null!=nodeList &amp;&amp; i &lt; nodeList.getLength(); i++) {
Node nod = nodeList.item(i);
//System.out.println(&quot;\n&quot;);
if(nod.getNodeType() == Node.ELEMENT_NODE){
NodeList arrayElements_18 = (NodeList) xpath.evaluate(&quot;/map/array[@key=&#39;planlagtAntallPerUndergruppe&#39;]/*&quot;, doc, XPathConstants.NODESET);
//System.out.println(&quot;\n number of elements&quot; + arrayElements_18.getLength());
for (int j = 0; j &lt; arrayElements_18.getLength(); j++) {
//.  antall
Node antall = (Node) xpath.evaluate(&quot;(/map/array/map/number[@key=&#39;antall&#39;])[1]&quot;, doc, XPathConstants.NODE);
antall.setTextContent(planlagtAntallPerUndergruppe_antall_value[j]);
// end antall
//.  kode
Node kode = (Node) xpath.evaluate(&quot;(/map/array/map/string[@key=&#39;kode&#39;])[1]&quot;, doc, XPathConstants.NODE);
kode.setTextContent(planlagtAntallPerUndergruppe_kode_value[j]);
//System.out.println(&quot;\n\n antall: &quot; + planlagtAntallPerUndergruppe_antall_value[j]);
// end kode                       
}                    
}
}
}
// end array planlagtAntallPerUndergruppe
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
System.out.println(&quot;Done Updating The Api_XML_Format.xml&quot;);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
} catch (XPathExpressionException xee) {
xee.printStackTrace();
}
}
}

答案1

得分: 1

根据给定的代码,planlagtAntallPerUndergruppe 的 NodeList 大小为 1。因为你选择了 <planlagtAntallPerUndergruppe> 元素。

NodeList planlagtAntallPerUndergruppe = document.getElementsByTagName("planlagtAntallPerUndergruppe");

因此,在循环中,声明的数组仅收集来自 FromThis.xml 文件中第一个 <element> 的值。

<element>
    <antall>67</antall>
    <kode>SLAKTEGRIS</kode>
</element>

解决方案

<element> 的 NodeList 获取为 planlagtAntallPerUndergruppe,如下所示:

NodeList planlagtAntallPerUndergruppe = document.getElementsByTagName("element");
英文:

as per the given code, planlagtAntallPerUndergruppe NodeList size is a one. because you select the &lt;planlagtAntallPerUndergruppe&gt; element.

NodeList planlagtAntallPerUndergruppe = document.getElementsByTagName(&quot;planlagtAntallPerUndergruppe&quot;);

hence, in the for loop, declared arrays collect the first &lt;element&gt; values only from FromThis.xml file.

&lt;element&gt;
&lt;antall&gt;67&lt;/antall&gt;
&lt;kode&gt;SLAKTEGRIS&lt;/kode&gt;
&lt;/element&gt;

Solution

get the &lt;element&gt; NodeList into planlagtAntallPerUndergruppe as follows,

NodeList planlagtAntallPerUndergruppe = document.getElementsByTagName(&quot;element&quot;);

huangapple
  • 本文由 发表于 2020年9月10日 20:19:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63829532.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定