How to extract xml attribute values in java - java

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;
}

Related

get key value Pairs from XML file in Java

I have to get Key and values from XMl File, I am getting Key but not value
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("laptops.xml"));
document.getDocumentElement().normalize();
NodeList laptopList = document.getElementsByTagName("string");
for(int i = 0; i <laptopList.getLength(); i++) {
Node laptop = laptopList.item(i);
if(laptop.getNodeType() == Node.ELEMENT_NODE) {
Element laptopElement = (Element) laptop;
System.out.println(laptopElement.getAttribute("name"));
}
}
XML File:
<laptops>
<string name="usb">100</string>
<string name="charger">200</string>
</laptops
Result Should be Like this :
usb: 100,
charger: 200
The values 100 and 200 are in Textnodes. You can get the content with:
laptopElement.getTextContent()

Is it possible to parse xml not by file name but its content (string value)?

Good Day,
Is it possible to parse XML content by not using its absolute path?
So it goes like this I have two variables:
replyInXml = "<company><staff id="1001"><firstname>yong</firstname><lastname>mook kim</lastname><nickname>mkyong</nickname><salary>100000</salary></staff></company>"
xmlFilePath = "c:\folder\file.xml"
In my Java code, I use the absolute path and I got the xml result I wanted. My question is, is it possible to parse it using the converted xml string (replyInXml) variable above.
File fXmlFile = new File(xmlFilePath);
Full Code:
public class XmlReader {
public String showProcessFlowID(String replyInXML) {
String processFlowResult = "";
try {
File fXmlFile = new File(replyInXML);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("SUIFT:TEST_ATTR_LIST");
// System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String processStep = "PROCESS STEP=" + eElement.getElementsByTagName("SUIFT:TEST_STAGE").item(0).getTextContent();
String flowID = "FLOW ID=" + eElement.getElementsByTagName("SUIFT:FLOW_ID").item(0).getTextContent();
processFlowResult = processStep + "\n" + flowID;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return processFlowResult;
}
public static void main(String args[]) {
//I want to use this but negative result since the File() parameter need xml file
String xmlContent = "<company><staff><firstname>yong</firstname><lastname>mook kim</lastname><nickname>mkyong</nickname><salary>100000</salary></staff></company>";
//This is working
String xmlPath = "C:\\folder1\\sampleReply.xml";
XmlReader processFlow = new XmlReader();
String reply = processFlow.showProcessFlowID(xmlPath);
System.out.println(reply);
}
}
Please advise.
TIA
Yes.You can user xml string to parse.
String xmlStr="";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream(xmlStr.getBytes("UTF-8")));

Getting an attribute value in xml generated from UML models

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());
}

Invalid answer while printing child elements from an XML file in JAVA

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);
}
}
}

Not able to parse the xml, Getting IOException

I am getting IOException for this line of code.
Response oresponse = orequest.send();
**This above Response object contains Xml data** :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<first-name>xyz</first-name>
<last-name>abc</last-name>
<api-standard-profile-request>
<url>http:[Removed]</url>
<headers total="1">
<http-header>
<name>[removed]</name>
<value>[removed]</value>
</http-header>
</headers>
</api-standard-profile-request>
</person>
And my parsing code is given below.
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(oresponse.getStream());
I am getting IOException for this last line i.e dBuilder.parse(oresponse.getStream()) . means during parsing. How can i parse this xml.It is giving me :
java.io.IOException: stream is closed.
at sun.net.www.http.ChunkedInputStream.ensureOpen(Unknown Source)
at sun.net.www.http.ChunkedInputStream.read(Unknown Source)
at java.io.FilterInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(Unknown Source)
Please try to use bellow code
public class Parser {
public static void parse(Context context, int type) {
try {
// File fXmlFile = new File("/root/Desktop/staff.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputStream catDoc = null;
ConstantLib.flashCardList = new ArrayList<FlashCardBean>();
Log.e("N", "TG " + type);
catDoc =context.getResources().openRawResource(R.raw.animal);
Document doc = dBuilder.parse(catDoc);
// optional, but recommended
// read this -
// http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("content");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
FlashCardBean cardBean = new FlashCardBean();
cardBean.setText(eElement.getElementsByTagName("text")
.item(0).getTextContent());
cardBean.setDetail(eElement.getElementsByTagName("detail")
.item(0).getTextContent());
cardBean.setImageSource(eElement
.getElementsByTagName("imgsource").item(0)
.getTextContent());
cardBean.setBorderColor(eElement
.getElementsByTagName("bordercolor").item(0)
.getTextContent());
cardBean.setMusicFile(eElement
.getElementsByTagName("imgsource").item(0)
.getTextContent().replace(".svg", ".mp3"));
ConstantLib.flashCardList.add(cardBean);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Categories