how to parse XML object in JAVA [duplicate] - java

I have the following code:
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
How can I get it to parse XML contained within a String instead of a file?

I have this function in my code base, this should work for you.
public static Document loadXMLFromString(String xml) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
return builder.parse(is);
}
also see this similar question

One way is to use the version of parse that takes an InputSource rather than a file
A SAX InputSource can be constructed from a Reader object. One Reader object is the StringReader
So something like
parse(new InputSource(new StringReader(myString))) may work.

Convert the string to an InputStream and pass it to DocumentBuilder
final InputStream stream = new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
builder.parse(stream);
EDITIn response to bendin's comment regarding encoding, see shsteimer's answer to this question.

I'm using this method
public Document parseXmlFromString(String xmlString){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes());
org.w3c.dom.Document document = builder.parse(inputStream);
return document;
}

javadocs show that the parse method is overloaded.
Create a StringStream or InputSource using your string XML and you should be set.

You can use the Scilca XML Progession package available at GitHub.
XMLIterator xi = new VirtualXML.XMLIterator("<xml />");
XMLReader xr = new XMLReader(xi);
Document d = xr.parseDocument();

Related

I am getting null pointer exception when i get the data from xml document using web service

String name= "Nsss";
String resulturl ="http://ssss/res/get?sid="+name+"";
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(resulturl));
Document doc = db.parse(resulturl);
System.out.println("sssssssssssssssssssssssssssssssssssssssssssssssssss"+doc.getDoctype().getTextContent());
I am getting this exception.
java.lang.NullPointerException
at com.controller.StudentsResultsController.main(ResultsController.java:130)
You should check to see what the resulturl variable is before you use it, but the other thing you need to address is: You are not using the InputSource at all. The following is likely to work better than what you have:
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(resulturl));
Document doc = db.parse(is);
EDIT
The Fatal Error is caused by the following:
StringReader(resulturl) takes a string argument that must be XML, not a filename or a URL. The parser is reading the value of the string variable, resulturl, and failing immediately because an XML document may not begin with an h character.
Try changing the above to:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new InputSource(resulturl));

Parse a specific XML [duplicate]

This question already has answers here:
java.net.MalformedURLException: no protocol
(2 answers)
Closed 5 years ago.
I want to parse XML in Java.
The XML looks like:
<Attributes><ProductAttribute ID="359"><ProductAttributeValue><Value>1150</Value></ProductAttributeValue></ProductAttribute><ProductAttribute ID="361"><ProductAttributeValue><Value>1155</Value></ProductAttributeValue></ProductAttribute></Attributes>
My try was:
public static void parseXml(String sb) throws Exception{
sb = "<Attributes><ProductAttribute ID="359"><ProductAttributeValue><Value>1150</Value></ProductAttributeValue></ProductAttribute><ProductAttribute ID="361"><ProductAttributeValue><Value>1155</Value></ProductAttributeValue></ProductAttribute></Attributes>";
Document dom;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(new InputSource(new ByteArrayInputStream(sb.getBytes("utf-8"))));
dom.toString();
}
I wanted first see, if the parsing is going. But it doesn't.
I get the error:
Premature end of file
Have anybody an idea, how can I parse these?
The question is not duplicate. I have read the answers of another question like my question, but the difference is the XML.
Thanks
First parse the JSON string to get the XML, then parse the xml. For instance, using JSON-java:
JSONObject obj = new JSONObject(json);
JSONArray arr = obj.getJSONArray("value");
for (Object elm: arr) {
String xml = ((JSONObject)elm).getString("AttributesXml");
DocumentBuilderFactory documentBuilderFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder
= documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(
new InputSource(new StringReader(xml)));
doSomethingWith(document);
}
But the method parse with a String argument expects an URI as the argument, not the XML source, so you must use another one.
UPDATE:
I see that you have updated your question, and the xml is in sb; this will be:
DocumentBuilderFactory documentBuilderFactory
= DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder
= documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(
new InputSource(new StringReader(sb)));
doSomethingWith(document);

xml and percent symbols

I'm using XMLStreamReader to parse a piece of xml:
XMLStreamReader rd = XMLInputFactory.newInstance().createXMLStreamReader(io_xml, "UTF-8");
...
if (eventType == XMLStreamConstants.START_ELEMENT) {
String name = rd.getLocalName();
if (name.equals("key")) {
String val = rd.getElementText();
}
}
Problem is, I'm getting a bad read for the following string: "<key>cami%C3%B5es%2Babc</key>"
org.junit.ComparisonFailure:
expected:<cami[%C3%B5es%]2Babc> but was:<cami[ C3 B5es ]2Babc>
Do I neeed to do anything special within the XML? I already tried to put everything within a CDATA section but I get the same error.
Using a "regular" parser everything works:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
Document parse = builder.parse(is);
String value = parse.getFirstChild().getTextContent();
...
I figured it out. The problem was in a different section of the code. A setter that didn't just set.

Create a FileReader from an XMLResponse?

I'm trying to create a FileReader (not a Document) from an XMLResponse like this :
// Parse XML Response
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = factory.newDocumentBuilder();
InputSource inStream = new InputSource();
inStream.setCharacterStream(new StringReader(XMLResponse));
Document doc = db.parse(inStream);
But I don't know how to use the InputSource to create it ?
You can't create a FileReader, because the response may not be coming from a file. But, as it seems, you can obtain a Reader, which is the proper way to refer to readers.
If a method requires specifically a FileReader, the method is not designed properly.

In Java, how do I parse XML as a String instead of a file?

I have the following code:
DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
How can I get it to parse XML contained within a String instead of a file?
I have this function in my code base, this should work for you.
public static Document loadXMLFromString(String xml) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
return builder.parse(is);
}
also see this similar question
One way is to use the version of parse that takes an InputSource rather than a file
A SAX InputSource can be constructed from a Reader object. One Reader object is the StringReader
So something like
parse(new InputSource(new StringReader(myString))) may work.
Convert the string to an InputStream and pass it to DocumentBuilder
final InputStream stream = new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8));
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
builder.parse(stream);
EDITIn response to bendin's comment regarding encoding, see shsteimer's answer to this question.
I'm using this method
public Document parseXmlFromString(String xmlString){
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes());
org.w3c.dom.Document document = builder.parse(inputStream);
return document;
}
javadocs show that the parse method is overloaded.
Create a StringStream or InputSource using your string XML and you should be set.
You can use the Scilca XML Progession package available at GitHub.
XMLIterator xi = new VirtualXML.XMLIterator("<xml />");
XMLReader xr = new XMLReader(xi);
Document d = xr.parseDocument();

Categories