Get Array from XML file stored in url - java

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

Related

Parsing XML into Android Application

I am trying to parse this XML onto my Android Application.
I read quite a few questions on parsing the XML here on stackoverflow, yet I am not sure how to handle a for loop everyone mentioned, in my case.
If someone would be nice enough to give me a working example for this case of XML, I'd be very grateful.
THE EXAMPLE CODE I FOUND ON STACKOVERFLOW
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(*/Insert my URL/*);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName(*/What to write here in my case?/*);
item = new TextView[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
item[i] = new TextView(this);
Element fstElmnt = (Element) node;
NodeList itemList = fstElmnt.getElementsByTagName(*/What to write here in my case?/*);
Element itemElement = (Element) itemList.item(0);
itemList = itemElement.getChildNodes();
item[i].setText("item = "
+ ((Node) itemList.item(0)).getNodeValue());
layout.addView(item[i]);
}
}
catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Set the layout view to display */
setContentView(layout);
}
The above code is NOT an example that I am using. It's just what I found on the internet how to parse XML on Android App. But my XML seems more complex than the ussually posted ones here.
use XmlPullParser for parsing XML in your android application. It is very easy to use and pretty fast.
I use XmlPullParser in all my applications.
Follow this tutorial it has nice example on how to use XmlPullParser.
http://www.vogella.com/tutorials/AndroidXML/article.html

Filling template xml in memory using Java and JDOM?

I want to create a XML from a template during runtime in Java using JDOM.
Below is a sample template
<PARENT>
<ISSUES>
<ISSUE id="ISSUE-X">
<SUMMARY></SUMMARY>
<CATEGORY></CATEGORY>
..
</ISSUE>
</ISSUES>
</PARENT>
I want to load this template file using Java + JDOM and get the following
<PARENT>
<ISSUES>
<ISSUE id="ISSUE-1">
<SUMMARY>Test 1</SUMMARY>
<CATEGORY>Cat 1</CATEGORY>
..
</ISSUE>
<ISSUE id="ISSUE-2">
<SUMMARY>Test 2</SUMMARY>
<CATEGORY>Cat 2</CATEGORY>
..
</ISSUE>
</ISSUES>
</PARENT>
Ideally I want to create more ISSUE nodes and fill the data from DB & save to file
Reason I thought I could use Template is because there will be additional nodes under <ISSUE> which I need to fill from db & was thinking filling this via template would be much faster
Can someone guide me on how to get this done in Java using JDOM?
Note: This template will adhere to a XSD which I haven't given here.
Thanks in advance
EDIT: Code snippet below
String sXMLPath = "D:\\WS\\issue_sample.xml";
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
org.w3c.dom.Document doc = dBuilder.parse(new File(sXMLPath));
DOMBuilder domBuilder = new DOMBuilder();
Document xConfigurationDocument;
xConfigurationDocument = domBuilder.build(doc);
XPathFactory xpfac = XPathFactory.instance();
XPathExpression<Element> xElements = xpfac.compile("//ns:MY-ISSUE/ns:ISSUES",Filters.element(),null,Namespace.getNamespace("ns", "http://www.myns.net/schemas/issue"));
List<Element> elements = xElements.evaluate(xConfigurationDocument);
for (Element xIssuesParent : elements) {
System.out.println(xIssuesParent.getName());
Element xCloneIssue = null ;
for (Element xIssueChild : xIssuesParent.getChildren())
{
xCloneIssue = xIssueChild.clone();
System.out.println(xIssueChild.getName());
xIssuesParent.removeContent(xIssueChild);
}
for (int i = 1; i < 3; i++) {
xCloneIssue.setAttribute("ID", "ISSUE-" + i);
xIssuesParent.addContent(xCloneIssue);
}
}
XMLOutputter xmlOutput = new XMLOutputter();
// display nice nice
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(xConfigurationDocument, new FileWriter("c:\\temp\\OutputFile.xml"));
I am trying out this in a sample application
The problem I face is that in the for loop (for (int i = 1; i < 3; i++)) after 1st I always get the following error The Content already has an existing parent "ISSUES"
Obviously what I am missing is a new clone.
My question is how can i always get a handle of an element and keep adding to the parent
If it will adhere to an XSD then take a look at org.jdom.input.DOMBuilder which you can parse a DTD into.

Null when parse XML document Android

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

How do I stop getNodeName() also printing the node type

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.

Using a string inside the DocumentBuilder parse method (need it for parsing XML using XPath) [duplicate]

This question already has answers here:
In Java, how do I parse XML as a String instead of a file?
(6 answers)
Closed 9 years ago.
I'm trying to create a RESTful webservice using a Java Servlet. The problem is I have to pass via POST method to a webserver a request. The content of this request is not a parameter but the body itself.
So I basically send from ruby something like this:
url = URI.parse(#host)
req = Net::HTTP::Post.new('/WebService/WebServiceServlet')
req['Content-Type'] = "text/xml"
# req.basic_auth 'account', 'password'
req.body = data
response = Net::HTTP.start(url.host, url.port){ |http| puts http.request(req).body }
Then I have to retrieve the body of this request in my servlet. I use the classic readline, so I have a string. The problem is when I have to parse it as XML:
private void useXML( final String soft, final PrintWriter out) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException, FileNotFoundException {
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true); // never forget this!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(soft);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath.compile("//software/text()");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
out.println(nodes.item(i).getNodeValue());
}
}
The problem is that builder.parse() accepts: parse(File f), parse(InputSource is), parse(InputStream is).
Is there any way I can transform my xml string in an InputSource or something like that? I know it could be a dummy question but Java is not my thing, I'm forced to use it and I'm not very skilled.
You can create an InputSource from a string by way of a StringReader:
Document doc = builder.parse(new InputSource(new StringReader(soft)));
With your string, use something like :
ByteArrayInputStream input =
new ByteArrayInputStream(yourString.getBytes(perhapsEncoding));
builder.parse(input);
ByteArrayInputStream is an InputStream.

Categories

Resources