Folks, I am trying to parse the below XML structure:
<root>
<data>
<doc>
<doc1></doc1>
<doc2></doc2>
</doc>
<INFO>
<INFO1></INFO1>
<INFO2></INFO2>
<INFO3></INFO3>
<INFO4></INOF4>
<ASSOC_SECTION>
<ASSOC_SECTION1>hello1</ASSOC_SECTION1>
<ASSOC_SECTION2></ASSOC_SECTION2>
</ASSOC_SECTION>
<ASSOC_SECTION>
<ASSOC_SECTION1>hello2</ASSOC_SECTION1>
<ASSOC_SECTION2></ASSOC_SECTION2>
</ASSOC_SECTION>
</INFO>
</data>
</root>
I am trying to read the values from the repeating node .
I am able to read the value of ASSOC_SECTION1 from the first repeating node, but while trying to read from the second node, I get a null pointer exception.
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, TransformerException {
// TODO Auto-generated method stub
File inputFile = new File(inputFile);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(inputFile);
document.getDocumentElement().normalize();
System.out.println("Root Element-->"+document.getDocumentElement().getNodeName());
NodeList nodeList = document.getElementsByTagName("ASSOC_SECTION");
System.out.println(nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
Node data = nodeList.item(i);
if(data.getNodeType() == Node.ELEMENT_NODE){
Element element = (Element) data;
System.out.println(element.getElementsByTagName("ASSOC_SECTION1").item(i).getTextContent());
}
}
Any idea as to why I am getting the null pointer issue here?
Related
I am trying to extract the xml values in java
Below is the xml and I want to extract userUuid from the xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ResponseSet vers="1.0" svcid="session" reqid="3">
<Response><![CDATA[
<SessionResponse vers="1.0" reqid="0">
<GetSession>
<Session sid="******" stype="user" cid="uid=****" cdomain="o=nhs" maxtime="0" maxidle="0" maxcaching="0" timeidle="0" timeleft="****" state="valid">
<Property name="userUuid" value="555524799109"></Property>
</Session>
</GetSession>
</SessionResponse>]]>
</Response>
</ResponseSet>
I referred this links none of them worked from me
Read XML in Java with XML attributes
How can I read Xml attributes using Java?
Also I tried
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
dbFactory.setValidating(false);
DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
ByteArrayInputStream inputStream = new ByteArrayInputStream(sXMLData.getBytes("UTF-8"));
Document document = docBuilder.parse(inputStream);
NodeList nodeList = document.getElementsByTagName("Property");
System.out.println(nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element) nodeList.item(i);
String el = element.getAttribute("name");
System.out.println(el);
}
Just posting an answer if someone faces same issue
public String parseXMLResponse(String sXMLData) throws IOException, SAXException, ParserConfigurationException {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
dbFactory.setValidating(false);
DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
ByteArrayInputStream inputStream = new ByteArrayInputStream(sXMLData.getBytes("UTF-8"));
Document document = docBuilder.parse(inputStream);
NodeList nodeList = document.getElementsByTagName("Property");
String userUuId = null;
for (int i = 0; i < nodeList.getLength(); i++) {
Element element = (Element) nodeList.item(i);
String el = element.getAttribute("name");
if(el.equalsIgnoreCase("UserId"))
{
userUuId = element.getAttribute("value");
break;
}
}
return userUuId;
}
I have an xml string like this and I want to get attribute value of "Element/xmi:type/name". It means I want to retreive name of element of type- activity only in a loop for each element. How do I do that? I am using javax.xml.parsers library.
<element xmi:idref="EAID_53685791_7F62_48a2_8BE8_DB7513AC776A" xmi:type="uml:Activity" name="Return error value" scope="public">
<model package="EAPK_263A2FE8_8346_4d1e_A851_39B9D573143D" tpos="0" ea_localid="98" ea_eleType="element"/>
<properties isSpecification="false" sType="Activity" nType="0" scope="public" isAbstract="false"/>
<project author="shiva999" version="1.0" phase="1.0" created="2016-08-16 09:44:25" modified="2016-08-16 10:13:51" complexity="1" status="Proposed"/>
<code gentype="<none>"/>
<style appearance="BackColor=-1;BorderColor=-1;BorderWidth=-1;FontColor=-1;VSwimLanes=1;HSwimLanes=1;BorderStyle=0;"/>
<modelDocument/>
<tags/>
<xrefs/>
<extendedProperties tagged="0" package_name="Activity Model"/>
<links>
<ControlFlow xmi:id="EAID_873CF8C4_0192_4099_8F66_6B36FA760AB6" start="EAID_53685791_7F62_48a2_8BE8_DB7513AC776A" end="EAID_D2EB427B_3AFD_4700_BD72_13B36684E595"/>
<ControlFlow xmi:id="EAID_2FECE2AE_6CA0_48a4_82AE_D743D257F37C" start="EAID_0D85B784_4393_429e_9BA1_7983BD7891CA" end="EAID_53685791_7F62_48a2_8BE8_DB7513AC776A"/>
</links>
</element>
Below is the code which I have written. Getting error as "The method type(int) is undefined for the type NodeLis". I am new to xml parsing and is refering online tutorials
public class DomXMLParser {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("activity.xml"));
NodeList nodeList = document.getElementsByTagName("Type");
for(int x=0,size= nodeList.getLength(); x<size; x++) {
System.out.println(nodeList.type(x).getAttributes().getNamedItem("name").getNodeValue());
}
}
}
Below is the code used using XPath. Not getting the expected result. I have many such activity nodes and transition edges for those. So I need to store them as a list and create a hierarchial graph.
public class DomXMLParser {
public static void main(String[] args) throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
//DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
File fXmlFile = new File("C:/Projekte/activity.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
javax.xml.xpath.XPathExpression expr
= xpath.compile("//xmi:XMI[xmi:type ='uml:Activity']/name/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
I have an xml file having data which looks like given below:
....
<ems:MessageInformation>
<ecs:MessageID>2147321820</ecs:MessageID>
<ecs:MessageTimeStamp>2016-01-01T04:38:33</ecs:MessageTimeStamp>
<ecs:SendingSystem>LD</ecs:SendingSystem>
<ecs:ReceivingSystem>CH</ecs:ReceivingSystem>
<ecs:ServicingFipsCountyCode>037</ecs:ServicingFipsCountyCode>
<ecs:Environment>UGS-D8UACS02</ecs:Environment>
</ems:MessageInformation>
....
There are many other nodes also. All nodes have namespace like ecs,tns,ems etc. I am suing following code part to extract all node names without namespace.
public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, TransformerException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("C:\\Users\\DadMadhR\\Desktop\\temp\\EDR_D3A0327.XML"));
NodeList nodeList = document.getElementsByTagName("*");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
//System.out.println(node.getNodeName());
System.out.println(node.getLocalName());
}
}
But when I execute this code, it's printing null for individual node. Can someone tell me what I am doing wrong here?
I read on internet and I came to know that node.getLocalName() will give node name without namespace. What is wrong then in my case?
You need to set the document builder factory to be namespace aware first. Then getLocalName() will start returning non-null values.
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.setNamespaceAware(true); // <=== here
Document document = docBuilder.parse(new File("C:\\Users\\DadMadhR\\Desktop\\temp\\EDR_D3A0327.XML"));
Given the following XML (example):
<?xml version="1.0" encoding="UTF-8"?>
<rsb:VersionInfo xmlns:atom="http://www.w3.org/2005/Atom" xmlns:rsb="http://ws.rsb.de/v2">
<rsb:Variant>Windows</rsb:Variant>
<rsb:Version>10</rsb:Version>
</rsb:VersionInfo>
I need to get the values of Variant and Version. My current approach is using XPath as I cannnot rely on the given structure. All I know is that there is an element rsb:Version somewhere in the document.
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "//Variant";
InputSource inputSource = new InputSource("test.xml");
String result = (String) xpath.evaluate(expression, inputSource, XPathConstants.STRING);
System.out.println(result);
This however does not output anything. I have tried the following XPath expressions:
//Variant
//Variant/text()
//rsb:Variant
//rsb:Variant/text()
What is the correct XPath expression? Or is there an even simpler way getting to this element?
I would suggest just looping through the document to find the given tag
public static void main(String[] args) throws SAXException, IOException,ParserConfigurationException, TransformerException {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document document = docBuilder.parse(new File("test.xml"));
NodeList nodeList = document.getElementsByTagName("rsb:VersionInfo");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
// do something with the current element
System.out.println(node.getNodeName());
}
}
}
Edit: Yassin pointed out that it won't get child nodes. This should point you in the right direction for getting the children.
private static List<Node> getChildren(Node n)
{
List<Node> children = asList(n.getChildNodes());
Iterator<Node> it = children.iterator();
while (it.hasNext())
if (it.next().getNodeType() != Node.ELEMENT_NODE)
it.remove();
return children;
}
Im trying to get the number of child elements of a parent element from a XML file using JAVA. Here is the code I'm working with:
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);
And here is the XML file:
<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>
The problem im facing is that it is printing a wrong value. The value printed is 13. But as you can see there are only 6 child elements for the parent element "TestCase". Where did i go wrong. Please help
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();
}
}
There are some white space charcters in your XML which will result in extra nodes. Try the above solution hope it helps.
The children of a node include whitespace text nodes as well as child element nodes.
Why not just do this with XPath - it's so much less hassle!
With Saxon and XPath 2.0 it would be
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());
Found the answer for the question. It works. The problem i had was ELEMENT_NODE. We have to filter ELEMENT_NODE. Here is the working code. Thanks for all those who helped be over there.
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);
}
}
}