Parse XML by referenceing parent node by using a variable - java

I am trying to use a variable that specifies which parent.child nodes I am parsing.
below is my current xml:
<results>
<GW>
<result>
<item>Car</item>
<name>Bob</name
</result>
<result>
<item>Bike</item>
<name>Tom</name
</result>
</GW>
<BF>
<result>
<item>Apple</item>
<name>Mike</name
</result>
<result>
<item>Melon</item>
<name>Julia</name
</result>
</BF>
</results>
And here is my parsing code. I want to use the variable items to tell which node I am supposed to parse GW or BF
//DOC IS ASSIGNED THE XML DATA EARLIER IN THE CODE
Bundle bundle = getIntent().getExtras();
int ITEMS = bundle.getInt("selection");
NodeList nodes = doc.node[ITEMS].getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("main_content", XMLfunctions.getValue(e, "item"));
map.put("name", XMLfunctions.getValue(e, "name"));
mylist.add(map);
}
I am trying to only parse either the child nodes of GW or BF and that depends on the value of ITEMS. So if items is equal to 0 then I would get the data from GW and if it is 1 I would get the data from BF.
If I could guess it would be something like:
NodeList nodes = doc.childNode[ITEMS].getElementsByTagName("result");

Element docElem = doc.getDocumentElement();
NodeList nl = docElem.getElementsByTagName("results");
Element elem = (Element)nl.item(ITEMS);
nodes = elem.getElementsByTagName("result");

Related

Java, XPath Expression to read all node names, node values, and attributes

I need help in make an xpath expression to read all node names, node values, and attributes in an xml string. I made this:
private List<String> listOne = new ArrayList<String>();
private List<String> listTwo = new ArrayList<String>();
public void read(String xml) {
try {
// Turn String into a Document
Document document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));
// Setup XPath to retrieve all tags and values
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document, XPathConstants.NODESET);
// Iterate through nodes
for(int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
listOne.add(node.getNodeName());
listTwo.add(node.getNodeValue());
// Another list to hold attributes
}
} catch(Exception e) {
LogHandle.info(e.getMessage());
}
}
I found the expression //text()[normalize-space()=''] online; however, it doesn't work. When I get try to get the node name from listOne, it is just #text. I tried //, but that doesn't work either. If I had this XML:
<Data xmlns="Somenamespace.nsc">
<Test>blah</Test>
<Foo>bar</Foo>
<Date id="2">12242016</Date>
<Phone>
<Home>5555555555</Home>
<Mobile>5555556789</Mobile>
</Phone>
</Data>
listOne[0] should hold Data, listOne[1] should hold Test, listTwo[1] should hold blah, etc... All the attributes will be saved in another parallel list.
What expression should xPath evaluate?
Note: The XML String can have different tags, so I can't hard code anything.
Update: Tried this loop:
NodeList nodeList = (NodeList) xPath.evaluate("//*", document, XPathConstants.NODESET);
// Iterate through nodes
for(int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
listOne.add(i, node.getNodeName());
// If null then must be text node
if(node.getChildNodes() == null)
listTwo.add(i, node.getTextContent());
}
However, this only gets the root element Data, then just stops.
//* will select all element nodes, //#* all attribute nodes. However, an element node does not have a meaningful node value in the DOM, so you would need to read out getTextContent() instead of getNodeValue.
As you seem to consider an element with child elements to have a "null" value I think you need to check whether there are any child elements:
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse("sampleInput1.xml");
XPathFactory fact = XPathFactory.newInstance();
XPath xpath = fact.newXPath();
NodeList allElements = (NodeList)xpath.evaluate("//*", doc, XPathConstants.NODESET);
ArrayList<String> elementNames = new ArrayList<>();
ArrayList<String> elementValues = new ArrayList<>();
for (int i = 0; i < allElements.getLength(); i++)
{
Node currentElement = allElements.item(i);
elementNames.add(i, currentElement.getLocalName());
elementValues.add(i, xpath.evaluate("*", currentElement, XPathConstants.NODE) != null ? null : currentElement.getTextContent());
}
for (int i = 0; i < elementNames.size(); i++)
{
System.out.println("Name: " + elementNames.get(i) + "; value: " + (elementValues.get(i)));
}
For the sample input
<Data xmlns="Somenamespace.nsc">
<Test>blah</Test>
<Foo>bar</Foo>
<Date id="2">12242016</Date>
<Phone>
<Home>5555555555</Home>
<Mobile>5555556789</Mobile>
</Phone>
</Data>
the output is
Name: Data; value: null
Name: Test; value: blah
Name: Foo; value: bar
Name: Date; value: 12242016
Name: Phone; value: null
Name: Home; value: 5555555555
Name: Mobile; value: 5555556789

java Convert Element to string

I am looking to get only the tag name, and not it's children.
I have an xml like this:
<RESPONSE>
<RESULT> !--TableName
<ADDRESS1>123 Main Street</ADDRESS1> !--ColumnName
<ZIP>12345</ZIP> !--ColumnName
</RESULT>
<RESULT> !--TableName
<ADDRESS1>245 Elm Street</ADDRESS1> !--ColumnName
<ZIP>45678</ZIP> !--ColumnName
</RESULT>
<VIN> !--TableName
<VIN_NUM>1K45678RTW23</VIN> !--ColumnName
</VIN>
….
</REPSONSE>
I am trying to dynamically save the xml into it's appropriate table and column names. So, I want to extract whatever the first element is, and assign it to a table name variable, and then it's children as columns.
Here is what I am doing so far:
private void extractToTableSet(Document doc, int appseqno ) throws Exception
{
NodeList responseList = doc.getElementsByTagName("RESPONSE");
for (int i = 0; i < responseList.getLength(); i++) {
Node currentNode = responseList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
Element tableElement = (Element) responseList.item(i);
if (tableElement != null && tableElement.hasChildNodes()) {
for (columnNode = tableElement.getFirstChild(); columnNode != null; columnNode = columnNode.getNextSibling()) {
if (columnNode.getNodeType() == Node.TEXT_NODE) {
columnName = columnNode.getNodeValue;
}
}
}
}
}
}
This way I am only able to get the values in the child nodes. Is there a way to get the name of the Element tags? Like I want to extract the value RESULT from the Document object.
In DOM, an element name is retrieved using Node.getNodeName().
Example:
if(node.getNodeType() == Node.ELEMENT_NODE) {
String elementName = node.getNodeName();
...
}
To get element's tagname :
Element tableElement = (Element) responseList.item(i);
String tagname = tableElement .getTagName();

how to count number of item in XMl item (Node List)

ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); // getting XML
int displayPerPage = 5;
int TotalRows = xml.length();
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
// adding HashList to ArrayList
menuItems.add(map);
}
This is my Code i want to Count nUmber of node i m not able to do this please tell me how i will do it http://api.androidhive.info/pizza/?format=xml suppose this my xml contaion 10 item or Node how i will count please post me code for that
Just use nl.getLength(), it'll return you the number of items in each tag.
You can use something like
NodeList list = doc.getElementsByTagName("item");
System.out.println("Total of elements : " + list.getLength());
Take a look at this tutorial.

how to Print date and id in given XML

This is my xml format:
<taxmann>
<docdetails>
<info id="104010000000006516" date="20120120">
<physicalpath>\\192.168.1.102\CMS\DATA</physicalpath>
<filepath isxml="N">\CIRCULARS\DIRECTTAXLAWS\HTMLFILES\CIRDGBACDD4836150012011122012012.htm</filepath>
<summary></summary>
<description></description>
<heading>DGBA.CDD. NO.H- 4836 /15.02.001/2011-12 | Clarification on Regulation of Interest Rates for Small Savings Schemes</heading>
<correspondingcitation/>
<hasfile>YES</hasfile>
<sortby>20120328155728957</sortby>
<parentid></parentid>
<parentchapterid></parentchapterid>
</info>
</docdetails>
</taxmann>
I'm able to retrieve data of heading but I want to print date and id too but I'm not able to do this. Please tell me how to implement it.
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for (int i = indexRowStart; i < indexRowEnd; i++) {
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map = new HashMap<String, String>();
map.put("RowID", String.valueOf(RowID));
String Heading= parser.getValue(e, KEY_NAME).replace("|", "|\n").replace("|", "");
map.put(KEY_NAME,Heading);
// adding HashList to ArrayList
menuItems.add(map);
}
This is my code please tell me the logic how I can parse, so that I can get date and id too.
Are you sure this is the easiest way to read that xml file? It just looks a bit too complicated. Why don't you navigate manually through the tree structure?
I would say you would get it this way:
SAXBuilder builder = new SAXBuilder();
Document doc;
doc = builder.build(file);
//rootElement would be your "taxmann" element
Element rootElement = doc.getRootElement();
Element docdetailsElement = rootElement.getChild("docdetails");
Element infoElement = docdetailsElement.getChild("info");
String id = infoElement.getAttributeValue("id");
String date = infoElement.getAttributeValue("date");
You should use Element#getAttribute(String name) method. In your case something like:
String id=e.getAttribute("id");
String date=e.getAttribute("date");

update data in java class as per change in attribute in the xml file

I want to add an attribute to the xml defination file
Now i want this change to be reflected in a java class . Can you suggest as to how it can be done . Also i want to add this attribute as a data member in one java class with it;s getter and setters . That i have done . I want to know how to assign the value from the node of the xml into the java attribute in this class . Please tell me only logic .
As you already have a schema for your xml files and you want java classes for the data types, consider using JAXB. This xml binding API can autogenerate classes from schemas and it provides convenient methods to marshal and unmarschal XML documents. (IAW: "convert an XML into java instances and vice versa).
Try to implement using this code
your attribute.xml
<attributes>
<attribute-list>
<attribute>
<fname>riddhish</fname>
<lname>chaudhari</lname>
</attribute>
</attribute-list>
<attributes>
Class File
public static final String ATTRIBUTE_LIST = "ATTRIBUTE_LIST";
public static final String ATTRIBUTE = "ATTRIBUTE";
public static final String FNAME = "FNAME";
Code for rading attributes from xml file
Document document = null;
NodeList nodeList = null;
Node node = null;
nodeList = document.getElementsByTagName("----file attributes.xml---").item(0).getChildNodes();
HashMap <String,Object> localParameterMap = new HashMap<String,Object>();
for(int i=0; i<nodeList.getLength(); i++){
node = nodeList.item(i);
if(node.getNodeName().equals("attribute-list")){
Collection objCollection = readAttributeList(node);
localParameterMap.put(ATTRIBUTE_LIST, objCollection);
}
}
function() readAttributeList
private Collection readAttributeList(Node node){
Collection<Object> objCollection = new ArrayList<Object>();
NodeList nodeList = node.getChildNodes();
for(int i=0; i < nodeList.getLength(); i++){
Node subNode = nodeList.item(i);
if(subNode.getNodeName().equals("attribute")){
NodeList attributeList = subNode.getChildNodes();
HashMap <String,Object> attributeMap = new HashMap<String,Object>();
for(int j=0; j<attributeList.getLength(); j++){
Node attributeNode = attributeList.item(j);
if(attributeNode.getNodeName().equals("fname")){
attributeMap.put(FNAME, attributeNode.getTextContent().trim());
}
}
}
objCollection.add(attributeMap);
}
return objCollection;
}
for reading attribute values in variable
String strfname = null;
if(map.get(CLASS_NAME.FNAME) != null) {
strfname = (String)map.get(CLASS_NAME.FNAME);
}

Categories

Resources