i'm parsing an xml document like this:
InputStream raw = getApplicationContext().getAssets().open("pubs.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder= dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(raw);
NodeList lista = doc.getElementsByTagName("name");
for(int i =0; i < lista.getLength(); i++)
titulos.add(lista.item(i).getNodeValue());
well, when i look into my final list (titulos) all is null, and i don't know why, cause it takes some time to parse the XML document :/ what i am doing wrong?
Thank you in advance
As shown in the Java documentation, the node value of an element is always null. Instead, you need to retrieve the text content of the element. Does this work any better?
for(int i =0; i < lista.getLength(); i++)
titulos.add(lista.item(i).getTextContent());
Related
I have an xml string stored in a StringBuilder.
My xml looks like this
couldn't write it in code so here's a screenshot
inside the report tag, it looks like
what it looks like
I would like to get access to any tag value I want in the record tag, what I have is :
StringBuilder informationString = new StringBuilder();
Scanner scanner = new Scanner(url.openStream());
while (scanner.hasNext()) {
informationString.append(scanner.nextLine());
}
//Close the scanner
scanner.close();
System.out.println(informationString);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(String.valueOf(informationString))));
Element rootElement = document.getDocumentElement();
But I do not know what to do with this and am very lost
Thanks by advance for helping
In general, you can use the below routine
Element documentElement=....
NodeList elmList=documentElement.getElementsByTagName("elementName");
Element e=(Element)elmList.itm(x);//putting it in a loop would do
You could keep using the above to get elements recursively.
Though a better approach would be to use XPath (Saxon has a decent XPath implementaton, though there are many more libraries to choose from)
I am trying to get all arrays I store in: https://s3.eu-west-2.amazonaws.com/tekstpieprz/strings.xml
I would like to use them for my textviews. I have added Unirest but cannot get my head around JSON. I have tried to play with something like:
HttpResponse<JsonNode> request = (HttpResponse<JsonNode>) Unirest.get("https://s3.eu-west-2.amazonaws.com/tekstpieprz/strings.xml")
.getBody("docukrz");
JSONObject myObj = request.getBody().getObject();
final JSONArray results = myObj.getJSONArray(String docukrz);
so then I can use the array in:
final String[] docukrz = res.getStringArray(R.array.docukrz);
But instead using
Resources
I would like to use the array I store online.
I do not fully understand how JSON works, I have only started learning JAVA 6 weeks ago. Any help would be much much appreciated.
You can find XML prase example here How can I parse xml from url in android?.
according to that answer, your code should be like below
URL url = new URL("https://s3.eu-west-2.amazonaws.com/tekstpieprz/strings.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("docukrz");
ArrayList resourceList = new ArrayList();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
resourceList.add(node);
}
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
I have next simple part of code:
String test = "<?xml version="1.0" encoding="UTF-8"?><TT_NET_Result><GUID>9145b1d3-4aa3-4797-b65f-9f5e00be1a30</GUID></TT_NET_Result>"
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(test)));
NodeList nl = doc.getDocumentElement().getElementsByTagName("TT_NET_Result");
The problem is that I don't get any result - nodelist variable "nl" is empty.
What could be wrong?
You're asking for elements under the document element, but TT_NET_Result is the document element. If you just call
NodeList nl = doc.getElementsByTagName("TT_NET_Result");
then I suspect you'll get the result you want.
Here's another response to this old question. I hit a similar issue in my code today and I actually read/write XML all the time. For some reason I overlooked one major fact. If you want to use
NodeList elements = doc.getElementsByTagNameNS(namespace,elementName);
You need to parse your document with a factory that is namespace-aware.
private static DocumentBuilderFactory getFactory() {
if (factory == null){
factory = DocumentBuilderFactory
.newInstance();
factory.setNamespaceAware(true);
}
return factory;
}
I'm stumped, hopefully I've just done a dumb thing that I can fix easily.
I'm passing in a String full of XML, being 'XMLstring'. I want to get one of the elements and print the child nodes in a "name = value" on the console. The problem is that the console keeps printing garbage along with the element name that I cannot work out how to get rid of.
Anyway, this code:
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(XMLstring));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("client-details");
Node node = nodes.item(0);
NodeList client_details = node.getChildNodes();
for (int i = 0; i < client_details.getLength(); i++) {
System.out.println(client_details.item(i).getNodeName()+" = "+getTextContents(client_details.item(i)));
}
}
catch (Exception e) {
e.printStackTrace();
}
Gives me the following:
#text =
testing-mode = false
#text =
name = testman
#text =
age = 30
Why is it printing the "#text ="? How do I get rid of it?
I am using NetBeans if that helps.
You want to use getNodeValue() instead:
System.out.println(client_details.item(i).getNodeValue()+" = "+getTextContents(client_details.item(i)));
If you look in the table at the top of this page, you see that for Text nodes, getNodeName() returns #text.
I am curious to see what each of the two function calls in your System.out.println() is printing out separately, only because the entire output should be on one line. One of those two is causing the problems, and i believe it may be internal to the function.
Otherwise, if you use String splitString = string.split("[=]"); it will split up the line based on the delimeter '='
then you can
String splitString = string.split("[=]");
System.out.println(splitString[1] + " = " + splitString[2]);
or, much more simply, make that one small edit that #retrodrone posted
OK I managed to resolve this issue, for anyone else who cares. The problem with the code is that the Node needs to be cast to an Element before you can get the tag name out of it in this manner. Therefore:
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(XMLstring));
Document doc = db.parse(is);
NodeList nodes = doc.getElementsByTagName("client-details");
Node node = nodes.item(0);
NodeList client_details = node.getChildNodes();
Element elementary;
for (int i = 0; i < client_details.getLength(); i++) {
if(client_details.item(i).getNodeType() == Node.ELEMENT_NODE) {
elementary = (Element) client_details.item(i);
System.out.println(elementary.getTagName()+" = "+getTextContents(client_details.item(i)));
}
}
}
Which produces the desired result, minus that "#text" bollocks :)
testing-mode = false
name = testman
age = 30
Notice the new "if" statement I added inside the for loop and the cast of the node to an element before calling getNodeName, which does work for Elements.