I have the below xml and I am trying to retrieve the value of id under BoostBuryDimensionValue tag using the java code but returns nothing.
Can some one help me on this. Thanks in advance.
Input XML
<?xml version="1.0" encoding="UTF-8"?>
<ContentItem type="OrganicZoneContent" xmlns="http://endeca.com/schema/content/2008" >
<TemplateId>OrganicResults</TemplateId>
<Name>OrganicResults</Name>
<Property name="navigation_records">
<BoostBury rollupKey="grp_id" recspecField="grp_id" xmlns="http://endeca.com/schema/content/xtags/2010">
<BoostBuryRecords>
<BoostBuryRecord recordType="CRITERIA" boostBuryType="BOOST">
<BoostBurySearch terms="null" key="null"/>
<BoostBuryDimensionValues>
<BoostBuryDimensionValue id="4294965238" name="career" dimensionName="Occasion"/>
</BoostBuryDimensionValues>
</BoostBuryRecord>
</BoostBuryRecords>
</BoostBury>
</Property>
</ContentItem>
and the java code i am using is
public static void main(String[] args) throws Exception {
InputStream xml = new FileInputStream("tempinput.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xml);
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("ContentItem/Property[#name='navigation_records']/BoostBury/BoostBuryRecords/BoostBuryRecord/BoostBuryDimensionValues/BoostBuryDimensionValue/#id");
Object result = expr.evaluate(doc, XPathConstants.STRING);
System.out.println("BoostBuryDimensionValue id = " + result);
}
Related
hi i am trying to read a xml which have namespace defined and some tags are with namespaces. But namespace tags always give empty value when i use XPath to read those tags.
Sample XML
<?xml version="1.0" encoding="UTF-8"?>
<Employees xmlns:ULAD="http://www.datamodelextension.org/Schema/ULAD">
<EXTENSION>
<OTHER>
<ULAD:HMDAGenderType>Male</ULAD:HMDAGenderType>
</OTHER>
</EXTENSION>
</Employees>
Sample Java Program to read ULAD:HMDAGenderType
public static void main(String args[]) throws XPathExpressionException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("C:\\test.xml");
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
XPathExpression expr = xpath.compile("/Employees/EXTENSION/OTHER/ULAD:HMDAGenderType");
System.out.println("Gender :: " + expr.evaluate(doc, XPathConstants.STRING));
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
}
Output :: null
Expected Output :: Male
How to read such tags ?
Try using XPath local-name()
Instead of
XPathExpression expr = xpath.compile("/Employees/EXTENSION/OTHER/ULAD:HMDAGenderType");
Please try
XPathExpression expr = xpath.compile("//*[local-name()='HMDAGenderType']");
And to get the text attribute value directly you can use this XPath:
XPathExpression expr = xpath.compile("//*[local-name()='HMDAGenderType']/text()");
The XML file is as :
Xml File
Code I have written:
List queryXmlUsingXpathAndReturnList(String xml, String xpathExpression) {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance()
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder()
Document doc = dBuilder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)))
doc.getDocumentElement().normalize()
XPath xPath = XPathFactory.newInstance().newXPath()
NodeList nodeList = (NodeList) xPath.compile(xpathExpression).evaluate(doc, XPathConstants.NODESET)
List returnElements = new ArrayList<>()
nodeList.each { n ->
returnElements.add(n.getTextContent())
}
When I am passing the xpath as:
/Envelope/Body/CommandResponseData/OperationResult/Operation/ParameterList/ListParameter/StringElement
It returns all the values.
But I want to return only the ListParameter values whose name="PackageTypeList".
For that I am using the xpath as:
/Envelope/Body/CommandResponseData/OperationResult/Operation/ParameterList/ListParameter[#name='PackageTypeList']/StringElement
But it returns list as null.
I guess you miss "CommandResult" between "CommandResponseData" and "OperationResult" in your XPath-Expression.
Below is the XML:-
<?xml version="1.0" encoding="utf-8"?>
<Stock>
<Identification>
<AccountID></AccountID>
<CustomerId></CustomerId>
</Identification>
<Product>
<ArticleName>Monitors</ArticleName>
<BaseUnit></BaseUnit>
<Notes></Notes>
<ID>11f13e2e-ae97-45b5-a9a9-23fa7f6bb767</ID>
<ID>b22834c0-a570-4e6b-97c3-5067a14d118d</ID>
<ID>ed458593-5e1a-4dc1-94f0-a66eeef2dd79</ID>
<ID>d25584a9-1db2-48cf-9a70-9b81e5a7e7f2</ID>
<LogisticalInfo>
<BaseUnit></BaseUnit>
<Compoundheight>4.78</Compoundheight>
<Compoundwidth>5.67</Compoundwidth>
<Compounddepth></Compounddepth>
<Compoundweight></Compoundweight>
<CompoundweightUnit>g</CompoundweightUnit>
<TotalHeight>30.5</TotalHeight>
<Totalwidth>542.7</Totalwidth>
<Totaldepth>37.5</Totaldepth>
<TotalWeight>2840</TotalWeight>
<height>mm</height>
<Weight>g</Weight>
<Depth>mm</Depth>
</LogisticalInfo>
</Product>
I would like to extract Compoundheight and Compounddepth, Below is the part of code to extract it but it is throwing error:java.lang.StringIndexOutOfBoundsException.
stringXmlDocument = productHeader + toStringXml(node, true) + productTrailer;
int CompoundheightCodeStart = stringXmlDocument.indexOf("<Compoundheight>");
int CompoundheightCodeEnd = stringXmlDocument.indexOf("</Compoundheight>"); height_packed=Double.parseDouble(stringXmlDocument.substring(CompoundheightCodeStart+13,CompoundheightCodeEnd));
int CompounddepthCodeStart = stringXmlDocument.indexOf("<Compounddepth>");
int CompounddepthCodeEnd = stringXmlDocument.indexOf("</Compounddepth>");depth_packed=Double.parseDouble(stringXmlDocument.substring(CompounddepthCodeStart+12, CompounddepthCodeEnd));
A better approach than indexOf would be to use Java XPath implementation for navigating XML.
See the Java XPath implementation, and the XPath Specification.
An example:
// parse the xml into a Document
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream inputStream = this.class.getResourceAsStream("test.xml");
Document document = builder.parse(inputStream);
// Obtain a specific element from within the Document
XPathFactory xPathFactory = XPathFactory.newInstance();
XPath xPath = xPathFactory.newXPath();
String articleName = xPath.evaluate("/Stock/Product/ArticleName", document);
System.out.println("ArticleName is: " + articleName);
The layout of my XML file is :
<?xml version="1.0" encoding="UTF-8"?>
<PasswordVault>
<User id="1">
<Log LOG="1">
<AccountType>asd</AccountType>
<Username>asd</Username>
<Password>asd</Password>
<E-mail>asd</E-mail>
</Log>
<Log Log="3">
<AccountType>as</AccountType>
<Username>as</Username>
<Password>as</Password>
<E-mail>as</E-mail>
</Log>
</User>
</PasswordVault>
And i have written the java code:
public class GetMaxLog {
public static void main(String[] args) throws Exception {
String y = x();
System.out.println(y);
}
public static String x() throws Exception{
try {
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = (Document)builder.parse("FILE PATH");
XPathFactory xpathfactory = XPathFactory.newInstance();
XPath xpath = xpathfactory.newXPath();
XPathExpression expr = xpath.compile("//PasswordVault/User[#id = 1]/Log[not(#LOG < ../Log/#LOG)]/#LOG");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
//returns the element at tag value 0 thus only the first set of data
return nodes.item(0).getNodeValue();
}catch(SAXParseException e){
return "0";
}
}
}
The function always return 1 when the maximum log value is clearly 3.How would i fix this function to always output the maximum log value.
XML names are case sensitive. The maximum value of #LOG is 1. To fix the issue you are having, change your data file from
<Log Log="3">
to
<Log LOG="3">
I'm building an application in Java and I have some problems with getting some values
The idea is that I have an XML document in the cloud (in this case Last.fm API), and I want to retrieve a value of a node, wich have an attribute. This value is a string, and I want to get it using the attribute
An example for Last.Fm XML is the following:
<track>
<id>1019817</id>
<name>Believe</name>
<mbid/>
<url>http://www.last.fm/music/Cher/_/Believe</url>
<duration>240000</duration>
<streamable fulltrack="1">1</streamable>
<listeners>69572</listeners>
<playcount>281445</playcount>
<artist>
<name>Cher</name>
<mbid>bfcc6d75-a6a5-4bc6-8282-47aec8531818</mbid>
<url>http://www.last.fm/music/Cher</url>
</artist>
<album position="1">
<artist>Cher</artist>
<title>Believe</title>
<mbid>61bf0388-b8a9-48f4-81d1-7eb02706dfb0</mbid>
<url>http://www.last.fm/music/Cher/Believe</url>
<image size="small">http://userserve-ak.last.fm/serve/34/8674593.jpg</image>
<image size="medium">http://userserve-ak.last.fm/serve/64/8674593.jpg</image>
<image size="large">http://userserve-ak.last.fm/serve/126/8674593.jpg</image>
</album>
<toptags>
<tag>
<name>pop</name>
<url>http://www.last.fm/tag/pop</url>
</tag>
...
</toptags>
<wiki>
<published>Sun, 27 Jul 2008 15:44:58 +0000</published>
<summary>...</summary>
<content>...</content>
</wiki>
</track>
So my idea is to get for example the image value with the attribute "medium"
I've done the following code using XMLPath:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document documento = builder.parse("http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=" + apikey + "&artist=cher&track=believe");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//lfm/track/album/image[#size='medium']");
NodeList nlLastFm = (NodeList) expr.evaluate(documento, XPathConstants.NODESET);
Element eLastFm = (Element) nlLastFm.item(0);
Log.i(TAG, "eLastFm: " + nlLastFm.item(0));
coverUrl = parser.getValue(eLastFm, "image");
But the problem is that it doesn't return correctly the value. I searched a lot of other posts related but they didn't solve my problem...
Could anybody help me?
Thanks for your help!
Try:
String value = nlLastFm.item(0).getTextContent()
A little test code(with smaller piece of your xml and xpath edited accordingly)
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException, XPathExpressionException {
String xml = "<album position=\"1\"><artist>Cher</artist><title>Believe</title><mbid>61bf0388-b8a9-48f4-81d1-7eb02706dfb0</mbid><url>http://www.last.fm/music/Cher/Believe</url><image size=\"small\">http://userserve-ak.last.fm/serve/34/8674593.jpg</image><image size=\"medium\">http://userserve-ak.last.fm/serve/64/8674593.jpg</image><image size=\"large\">http://userserve-ak.last.fm/serve/126/8674593.jpg</image></album>";
InputStream stream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document documento = builder.parse(stream);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//album/image[#size='medium']");
NodeList nlLastFm = (NodeList) expr.evaluate(documento,
XPathConstants.NODESET);
String coverUrl = nlLastFm.item(0).getTextContent();
System.out.println(coverUrl);
}
Outputs http://userserve-ak.last.fm/serve/64/8674593.jpg