简体   繁体   中英

Store xml values in arraylist in java

I have a xml as follows need to store the values of xml field in the array list can anybody help.

<Search>
<Fields>
<Field>
<IndexId>241</IndexId><IndexName>ProductCode</IndexName><IndexType>S</IndexType><IndexLength>100</IndexLength><IndexFlag>D</IndexFlag><UsefulInfoFlag>N</UsefulInfoFlag><UsefulInfosize>255</UsefulInfosize><IndexAttribute>0</IndexAttribute></Field>
<Field>
<IndexId>263</IndexId><IndexName>Partner Name</IndexName><IndexType>S</IndexType><IndexLength>100</IndexLength><IndexFlag>D</IndexFlag><UsefulInfoFlag>N</UsefulInfoFlag><UsefulInfosize>255</UsefulInfosize><IndexAttribute>0</IndexAttribute></Field>
<Field>
<IndexId>420</IndexId><IndexName>Day</IndexName><IndexType>S</IndexType><IndexLength>100</IndexLength><IndexFlag>D</IndexFlag><UsefulInfoFlag>N</UsefulInfoFlag><UsefulInfosize>255</UsefulInfosize><IndexAttribute>0</IndexAttribute></Field>
<Field>
<IndexId>421</IndexId><IndexName>Month</IndexName><IndexType>S</IndexType><IndexLength>100</IndexLength><IndexFlag>D</IndexFlag><UsefulInfoFlag>N</UsefulInfoFlag><UsefulInfosize>255</UsefulInfosize><IndexAttribute>0</IndexAttribute></Field>
</Fields>
</Search>

There is various Parser library you can use. reference link: https://www.tutorialspoint.com/java_xml/java_xml_parsers.htm

Here you go with one for them

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;


File inputFile = new File("input.txt");

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();

NodeList nList = doc.getElementsByTagName("Field");

for (int temp = 0; temp < nList.getLength(); temp++) {
    System.out.println(eElement.getAttribute("IndexId"));
    System.out.println(eElement.getAttribute("IndexName"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM