I want to convert a String to org.jdom.Element
String s = "<rdf:Description rdf:about=\"http://dbpedia.org/resource/Barack_Obama\">";
How can I do it?
There is more than one way to parse XML from string:
Example 1:
String xml = "Your XML";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new ByteArrayInputStream(xml.getBytes("UTF-8")));
Example 2:
Using a SAXParser which can read an inputsource:
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
saxParser.parse(new InputSource(new StringReader("Your XML")), handler);
See: SAXParser, InputSource
Create a Document from your string. Look at JDOM FAQ: How do I construct a Document from a String?
Use method Document.getRootElement() to access the root element.
(You mentioned package org.jdom so I assume you work with JDOM 1.1.)
I recommend you use the Simple XML Framework from http://simple.sourceforge.net/.With this framework you can serialize and deserialize your objects easily. I hope this information can be important for you.
Related
I am trying to format XML string to pretty. I want all the attributes to be printed in single line.
XML input:
<root><feeds attribute1="a" attribute2="b" attribute3="c" attribute4="d" attribute5="e" attribute6="f"> <id>2140</id><title>gj</title><description>ghj</description>
<msg/>
Expected output:
<root>
<feeds attribute1="a" attribute2="b" attribute3="c" attribute4="d" attribute5="e" attribute6="f">
<id>2140</id>
<title>gj</title>
<description>ghj</description>
<msg/>
</feeds>
Actual Output:
<root>
<feeds attribute1="a" attribute2="b" attribute3="c" attribute4="d"
attribute5="e" attribute6="f">
<id>2140</id>
<title>gj</title>
<description>ghj</description>
<msg/>
</feeds>
Here is my code to format xml. I have also tried SAX parser. I don't want to use DOM4J.
public static String formatXml(String xml) {
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS impl = (DOMImplementationLS) registry.getDOMImplementation("LS");
LSSerializer writer = impl.createLSSerializer();
writer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
writer.getDomConfig().setParameter("xml-declaration", false);
writer.getDomConfig().setParameter("well-formed", true);
LSOutput output = impl.createLSOutput();
ByteArrayOutputStream out = new ByteArrayOutputStream();
output.setByteStream(out);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(xml));
writer.write(db.parse(is), output);
return new String(out.toByteArray());
}
Is there any way to keep attributes in one line with SAX or DOM parser? I am not looking for any additional library. I am looking for solution with java library only.
A SAX or DOM parser will read your input string and allow your application to understand what was passed in. At some point in time your application then writes out that data, and that is the moment where you decide to insert additional whitespace (like linefeeds and tab characters) to pretty-print the document.
If you really want to use SAX and make the parser efficient the best you could do is write the document while it is being parsed. So you would implement the ContentHandler interface (https://docs.oracle.com/en/java/javase/11/docs/api/java.xml/org/xml/sax/ContentHandler.html) such that it directly writes out the data while adding linefeeds where you feel they belong to.
Check this tutorial to see how the ContentHandler can then be applied in a SAX parser: https://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html
I am receiving this string via servlet from javascript as such :
%3C%3Fxml+version%3D%221.0%22+encoding%3D%22UTF-8%22+standalone%3D%22no%22%3F%3E%3Crunningparameters%3E++%0A%09%3Caccesskey%3Eawd%3C%2Faccesskey%3E%0A%09%3Csecretkey%3ErL8cuC6GzH%2F8zHycg45sM47MqQMVVPmgZjdgDIJS%3C%2Fsecretkey%3E%0A%09%3Ckeyfile%3E%2FTdcGooglePrototype%2Fresources%2Ffrank_arianit_keypair.pem%3C%2Fkeyfile%3E%0A%09%3Creadybucketname%3Efa-initialbucket%3C%2Freadybucketname%3E%0A%09%3Cdonebucketname%3Efa-completedbucket%3C%2Fdonebucketname%3E%0A%09%3Cmanagertodownloader%3Ehttps%3A%2F%2Fsqs.eu-central-1.amazonaws.com%2F210890795349%2FFA_M2D%0A%09%3C%2Fmanagertodownloader%3E%0A%09%3Capplicationtomanager%3Ehttps%3A%2F%2Fsqs.eu-central-1.amazonaws.com%2F210890795349%2FFA_A2M%0A%09%3C%2Fapplicationtomanager%3E%0A%09%3Cpolicyconfig%3Ehttps%3A%2F%2Fsqs.eu-central-1.amazonaws.com%2F210890795349%2FFA_Policy%0A%09%3C%2Fpolicyconfig%3E%0A%09%3Cqueuelength%3E100%3C%2Fqueuelength%3E%0A%09%3Cnumberofdownloader%3E100%3C%2Fnumberofdownloader%3E%0A%09%3Cdownloadspeed%3E10%3C%2Fdownloadspeed%3E%0A%09%3Cpagerankthreshold%3E0.001%3C%2Fpagerankthreshold%3E%0A%09%3Ctotalpages%3E10000%3C%2Ftotalpages%3E%0A%09%3Cpagerankmaxloop%3E10%3C%2Fpagerankmaxloop%3E%0A%09%3Ccountryfilters%3E%0A%09%09%3Curlcountry%3Ecom%3C%2Furlcountry%3E%0A%09%3C%2Fcountryfilters%3E%0A%09%3Cfiletypefilters%3E++++++%0A%09%09%3Curlfiletype%3Epdf%3C%2Furlfiletype%3E%0A%09%09%3Curlfiletype%3Ehtml%3C%2Furlfiletype%3E++%0A%09%09%3Curlfiletype%3Ehtm%3C%2Furlfiletype%3E%0A%09%3C%2Ffiletypefilters%3E%0A%09%3Cseedurls%3E%0A%09%09%09%3Curl%3Ehttp%3A%2F%2Fwww.cnn.com%2F%3C%2Furl%3E+%09%0A%09%3C%2Fseedurls%3E%0A%3C%2Frunningparameters%3E
It's in xml but kinda look messed up. Is there a way to convert this to dom document ?
I tried :
Document d;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
d = parser.parse(xmlstring);
But it doesn't work because i know the string format looks crazy.
I am trying to write a code that helps me to create a XML object. For example, I will give a string as input to a function and it will return me a XMLObject.
XMLObject convertToXML(String s) {}
When I was searching on the net, generally I saw examples about creating XML documents. So all the things I saw about creating an XML and write on to a file and create the file. But I have done something like that:
Document document = new Document();
Element child = new Element("snmp");
child.addContent(new Element("snmpType").setText("snmpget"));
child.addContent(new Element("IpAdress").setText("127.0.0.1"));
child.addContent(new Element("OID").setText("1.3.6.1.2.1.1.3.0"));
document.setContent(child);
Do you think it is enough to create an XML object? and also can you please help me how to get data from XML? For example, how can I get the IpAdressfrom that XML?
Thank you all a lot
EDIT 1: Actually now I thought that maybe it would be much easier for me to have a file like base.xml, I will write all basic things into that for example:
<snmp>
<snmpType><snmpType>
<OID></OID>
</snmp>
and then use this file to create a XML object. What do you think about that?
If you can create a string xml you can easily transform it to the xml document object e.g. -
String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
} catch (Exception e) {
e.printStackTrace();
}
You can use the document object and xml parsing libraries or xpath to get back the ip address.
try something like
public static Document loadXML(String xml) throws Exception
{
DocumentBuilderFactory fctr = DocumentBuilderFactory.newInstance();
DocumentBuilder bldr = fctr.newDocumentBuilder();
InputSource insrc = new InputSource(new StringReader(xml));
return bldr.parse(insrc);
}
Im reading some RSS from an URL and are experiencing some troubles.
Initially I had a straightforward implementation like this:
SAXReader reader = new SAXReader();
Document doc = reader.read(new URL(sURL));
However, this didnt allow me to timeout the request if the response was very slow. So I changed it to :
public static org.dom4j.Document readXml(InputStream is) throws SAXException, IOException,
ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
dbf.setIgnoringComments(false);
dbf.setIgnoringElementContentWhitespace(true);
dbf.setNamespaceAware(true);
DocumentBuilder db = null;
db = dbf.newDocumentBuilder();
return (org.dom4j.Document)db.parse(is);
}
SAXReader reader = new SAXReader();
URL myUrl = new URL(sURL);
URLConnection c = myUrl.openConnection();
c.setConnectTimeout(10000);
c.setReadTimeout(10000);
org.dom4j.Document doc = readXml(c.getInputStream());
Element root = doc.getRootElement();
When trying this, I get a annyoing error:
org.apache.xerces.dom.DeferredDocumentImpl incompatible with org.dom4j.Document
How can I avoid this? None of the above methods are supposed to return that type of Document, and I also try to cast to the correct document type..
EDIT: The problem is db.parse(is) which returns org.w3c.dom ..
Make sure your Element is of type org.dom4j.Element and not org.w3c.dom, javax.bind.xml, etc.
In other words, dom4j API is not compatible with Java's built-in XML API. The two simply do not mix together, unless you operate with Strings (e.g. generate XML in dom4j and parse it with Java's XML or vice versa).
Problem solved!
By using :
DOMReader domReader = new DOMReader();
org.dom4j.Document dom4jDoc = domReader.read(doc);
org.dom4j.Element root = (Element)dom4jDoc.getRootElement();
To create an org.dom4j.Document from the org.w3c.dom.Document
I'm parsing (a lot of) XML files that contain entity references which i dont know in advance (can't change that fact).
For example:
xml = "<tag>I'm content with &funny; &entity; &references;.</tag>"
when i try to parse this using the following code:
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
final DocumentBuilder db = dbf.newDocumentBuilder();
final InputSource is = new InputSource(new StringReader(xml));
final Document d = db.parse(is);
i get the following exception:
org.xml.sax.SAXParseException: The entity "funny" was referenced, but not declared.
but, what i do want to achieve is, that the parser replaces every entity that is not declared (unknown to the parser) with an empty String ''.
Or even better, is there a way to pass a map to the parser like:
Map<String,String> entityMapping = ...
entityMapping.put("funny","very");
entityMapping.put("entity","important");
entityMapping.put("references","stuff");
so that i could do the following:
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
final DocumentBuilder db = dbf.newDocumentBuilder();
final InputSource is = new InputSource(new StringReader(xml));
db.setEntityResolver(entityMapping);
final Document d = db.parse(is);
if i would obtain the text from the document using this example code i should receive:
I'm content with very important stuff.
Any suggestions? Of course, i already would be happy to just replace the unknown entity's with empty strings.
Thanks,
The StAX API has support for this. Have a look at XMLInputFactory, it has a runtime property which dictates whether or not internal entities are expanded, or left in place. If set to false, then the StAX event stream will contain instances of EntityReference to represent the unexpanded entities.
If you still want a DOM as the end result, you can chain it together like this:
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
inputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
String xml = "my xml";
StringReader xmlReader = new StringReader(xml);
XMLEventReader eventReader = inputFactory.createXMLEventReader(xmlReader);
StAXSource source = new StAXSource(eventReader);
DOMResult result = new DOMResult();
transformer.transform(source, result);
Node document = result.getNode();
In this case, the resulting DOM will contain nodes of org.w3c.dom.EntityReference mixed in with the text nodes. You can then process these as you see fit.
Since your XML input seems to be available as a String, could you not do a simple pre-processing with regular expression replacement?
xml = "...";
/* replace entities before parsing */
for (Map.Entry<String,String> entry : entityMapping.entrySet()) {
xml = xml.replaceAll("&" + entry.getKey() + ";", entry.getValue());
}
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
...
It's quite hacky, and you may want to spend some extra effort to ensure that the regexps only match where they really should (think <entity name="&don't-match-me;"/>), but at least it's something...
Of course, there are more efficient ways to achieve the same effect than calling replaceAll() a lot of times.
You could add the entities at the befinning of the file. Look here for more infos.
You could also take a look at this thread where someone seems to have implemented an EntityResolver interface (you could also implement EntityResolver2 !) where you can process the entities on the fly (e.g. with your proposed Map).
WARNING: there is a bug! in jdk6, but you could try it with jdk5