Storing xml data in Java object using jaxb - java

<?xml version="1.0" encoding="UTF-8"?>
<filepaths>
<application_information_ticker>
<desc>Ticker1</desc>
<folder_path>../atlas/info/</folder_path>
</application_information_ticker>
<document_management_system>
<desc></desc>
<folder_path>../atlas/dms/</folder_path>
</document_management_system>
</filepaths>
I have a xml file like this. I need to convert this xml file into java object using JAXB. Because of nested tags, I couldn't perform the operation. Please suggest me a solution for this

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource( new StringReader( xmlString) );
Document doc = builder.parse( is );
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
xpath.setNamespaceContext(new PersonalNamespaceContext());
XPathExpression expr = xpath.compile("//src_small/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
List<String> list = new ArrayList<String>();
for (int i = 0; i < nodes.getLength(); i++) {
list.add (nodes.item(i).getNodeValue());
System.out.println(nodes.item(i).getNodeValue());

Related

Get Parent attribute value based XML search using xpath java

I want get RECORD number based on contract id passed to java method. can any one help on this as i am new to XML parsing?
sample xml file:
<?xml version="1.0"?><FILE>
<Document RECORD="1"><Contract-Id>234</Contract-Id><Client-Id>232</Client-Id></Document>
<Document RECORD="2"><Contract-Id>235</Contract-Id><Client-Id>334</Client-Id></Document>
</FILE?
Java code:
File fXmlFile = new File(inputFile);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document xmlDocument = dBuilder.parse(fXmlFile);
xmlDocument.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression xPathExpr = xPath.compile("//Document/Contract-Id[text()='"+ContractNumber+"']");
//Object result = xPathExpr.evaluate(xmlDocument,XPathConstants.NODESET);
Node nl = (Node)xPathExpr.evaluate(xmlDocument.getParentNode(), XPathConstants.NODESET);
nl.getTextContent();
nl.getAttributes();
Please try the following XPath expression:
/FILE/Document[Contract-Id="235"]/#RECORD

Java: XML dom parsing retrieves just 1 element of the array

I have the following XML (provided by a web service)
<?xml version="1.0" encoding="UTF-8"?>
<itam>
<status>OK</status>
<data>
<item0>
<id>246</id>
<prefisso_quadrato>1</prefisso_quadrato>
<id_incontro_corrente />
<id_giornata>65</id_giornata>
<round>R1</round>
<tempo>120</tempo>
<punti_chong>0</punti_chong>
<punti_hong>0</punti_hong>
<amm_chong>0</amm_chong>
<amm_hong>0</amm_hong>
</item0>
<item1>
<id>247</id>
<prefisso_quadrato>2</prefisso_quadrato>
<id_incontro_corrente />
<id_giornata>65</id_giornata>
<round>R1</round>
<tempo>120</tempo>
<punti_chong>0</punti_chong>
<punti_hong>0</punti_hong>
<amm_chong>0</amm_chong>
<amm_hong>0</amm_hong>
</item1>
<item2>
<id>248</id>
<prefisso_quadrato>3</prefisso_quadrato>
<id_incontro_corrente />
<id_giornata>65</id_giornata>
<round>R1</round>
<tempo>120</tempo>
<punti_chong>0</punti_chong>
<punti_hong>0</punti_hong>
<amm_chong>0</amm_chong>
<amm_hong>0</amm_hong>
</item2>
</data>
</itam>
I am trying to parse it in JAVA. I can access to the <status> and also to the <data> element. But when I try to iterate over <data> items, I can read just 1 element. This is the code:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);
doc.getDocumentElement().normalize();
System.out.println(doc.getDocumentElement().getElementsByTagName("data").getLength());
OUTPUT: 1
My idea was something like the code below, but it runs just over the first element (I can read the rest element attributes and then it ends). How can I fix it? Thank you very much
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);
doc.getDocumentElement().normalize();
NodeList nodelist = doc.getDocumentElement().getElementsByTagName("data");
if(nodelist!=null){
for(int i=0; i<nodelist.getLength(); i++){
Element el = (Element) nodelist.item(i);
//use el to get data from it
}
}
The error is that you are looking for a list of <data> element and you have just one. A solution can be:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document doc = builder.parse(is);
doc.getDocumentElement().normalize();
NodeList items = doc.getDocumentElement().getElementsByTagName("data").item(0).getChildNodes();
for(int i=0; i<items.getLength(); i++){
System.out.println(items.item(i).getNodeName());
}
Good luck!
You will have to recurively iterate over the xml file to get all the elements..
something like this
private Document getDocument(String xsdUrl)
throws ParserConfigurationException, SAXException, IOException {
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
final DocumentBuilder db = dbf.newDocumentBuilder();
final Document doc = db.parse(xsdUrl);
return doc;
}
private void processElementRecurse(final Element node) throws IOException,
ParserConfigurationException, SAXException, TransformerException {
final NodeList nl = node.getChildNodes();
for (int i = 0, n = nl.getLength(); i < n; i++) {
final Node childNode = nl.item(i);
if (childNode instanceof Element) {
}
else {
processElementRecurse(childElement);
}
}
}

delete the unwanted strings before and after the string in xml file

xml file content
<distributionChannels><distributionChannel type="Wap" id="1"><contentChannelRefs>
<contentChannelRef id="2"><categories><category
link="http://images/11.gif" id="1"><names><name lang="de">Top Downloads</name><name
lang="ww">Tops</name></names></category></categories></contentChannelRef>
</contentChannelRefs></distributionChannel>
</distributionChannels>
how do i delete the unwanted content which i am reading from an xml file and the output should look as shown below:
<category link="http://images/11.gif" id="1"><names><name lang="de">Top Downloads</name><name lang="ww">Tops</name></names></category>
Reliable solution - use an XML parser. Simple solution is
s = s.substring(s.indexOf("<categories>"), s.indexOf("</categories>") + 13);
if you want to read categories one by one use regex
Matcher m = Pattern.compile("<category.*?>.*?</category>").matcher(xml);
for(int i = 0; m.find(); i++) {
System.out.println(m.group());
}
Pattern matching with XML is not recommended. Use a parser to get your nodes and the manage them accordingly. If you are interested in printing them I have included code to print the nodes.
public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(s)));
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr
= xpath.compile("//categories//category");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
//This is where you are printing things. You can handle differently if
//you would like.
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodeToString(nodes.item(i)));
}
}
private static String nodeToString(Node node) {
StringWriter sw = new StringWriter();
try {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.transform(new DOMSource(node), new StreamResult(sw));
} catch (TransformerException te) {
te.printStackTrace();
}
return sw.toString();
}

How to retrieve/extract XML element attribute value

I have an XML like the following,
<?xml version="1.0" encoding="utf-8"?>
<PaymentElement>
<Payment seqID="3">
<TPayment>
<Status>status</Status>
</TPayment>
</Payment>
</PaymentElement>
The question is how do I retrieve/extract seqID value which is 3 out of this via java.
I have tried the following way, but it doesn't work.
InputStream xml = conn.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xml);
NodeList list = doc.getElementsByTagName("PaymentElement");
for(int i=0; i<=list.getLength();i++){
NodeList paySeq=doc.getElementsByTagName("Payment seqID");
System.out.println("Payment seqID"+paySeq);
}
try
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("1.xml"));
Element e = (Element)doc.getDocumentElement().getElementsByTagName("Payment").item(0);
String id = e.getAttribute("seqID");
System.out.println("Payment seqID = " + id);
output
Payment seqID = 3
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/PaymentElement/Payment/#seqID");
Object result = expr.evaluate(doc, XPathConstants.STRING);
result should be having 3 now.
Full Example
import java.io.*;
import javax.xml.xpath.*;
import org.xml.sax.InputSource;
public class Demo {
public static void main(String[] args) throws Exception {
InputStream inputStream = new FileInputStream("sample.xml");
InputSource inputSource = new InputSource(inputStream);
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/PaymentElement/Payment/#seqID");
Object result = expr.evaluate(inputSource, XPathConstants.STRING);
System.out.println(result);
}
}

Getting value of child node from XML in java

My xml file looks like this
<InNetworkCostSharing>
<FamilyAnnualDeductibleAmount>
<Amount>6000</Amount>
</FamilyAnnualDeductibleAmount>
<IndividualAnnualDeductibleAmount>
<NotApplicable>Not Applicable</NotApplicable>
</IndividualAnnualDeductibleAmount>
<PCPCopayAmount>
<CoveredAmount>0</CoveredAmount>
</PCPCopayAmount>
<CoinsuranceRate>
<CoveredPercent>0</CoveredPercent>
</CoinsuranceRate>
<FamilyAnnualOOPLimitAmount>
<Amount>6000</Amount>
</FamilyAnnualOOPLimitAmount>
<IndividualAnnualOOPLimitAmount>
<NotApplicable>Not Applicable</NotApplicable>
</IndividualAnnualOOPLimitAmount>
</InNetworkCostSharing>
I am trying to get Amount value from <FamilyAnnualDeductibleAmount> and also from <FamilyAnnualOOPLimitAmount>. How do i get those values in java?
You may use two XPath queries /InNetworkCostSharing/FamilyAnnualDeductibleAmount and InNetworkCostSharing/FamilyAnnualOOPLimitAmount or just get the node InNetworkCostSharing and retrieve the values of its two direct children.
Solution using XPath:
// load the XML as String into a DOM Document object
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream("YOUR XML".getBytes());
Document doc = docBuilder.parse(bis);
// XPath to retrieve the content of the <FamilyAnnualDeductibleAmount> tag
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xpath.compile("/InNetworkCostSharing/FamilyAnnualDeductibleAmount/text()");
String familyAnnualDeductibleAmount = (String)expr.evaluate(doc, XPathConstants.STRING);
StAX based solution:
XMLInputFactory f = XMLInputFactory.newInstance();
XMLStreamReader rdr = f.createXMLStreamReader(new FileReader("test.xml"));
while (rdr.hasNext()) {
if (rdr.next() == XMLStreamConstants.START_ELEMENT) {
if (rdr.getLocalName().equals("FamilyAnnualDeductibleAmount")) {
rdr.nextTag();
int familyAnnualDeductibleAmount = Integer.parseInt(rdr.getElementText());
System.out.println("familyAnnualDeductibleAmount = " + familyAnnualDeductibleAmount);
} else if (rdr.getLocalName().equals("FamilyAnnualOOPLimitAmount")) {
rdr.nextTag();
int familyAnnualOOPLimitAmount = Integer.parseInt(rdr.getElementText());
System.out.println("FamilyAnnualOOPLimitAmount = " + familyAnnualOOPLimitAmount);
}
}
}
rdr.close();
Note that StAX is especially good for cases like yours, it skips all unnecessary elements reading only the ones you need
Try something like this(use getElementsByTagName to get the parent nodes and then get the value be reaching out to child node):
File xmlFile = new File("NetworkCost.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile );
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("FamilyAnnualDeductibleAmount");
String familyDedAmount = nList.item(0).getChildNodes().item(0).getTextContent();
nList = doc.getElementsByTagName("FamilyAnnualOOPLimitAmount");
String familyAnnualAmount =
nList.item(0).getChildNodes().item(0).getTextContent();
I think I found the solution with this question from stackoverflow
Getting XML Node text value with Java DOM

Categories

Resources