Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a XML object from String in Java?

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?

like image 370
Ozer Avatar asked Sep 30 '11 07:09

Ozer


People also ask

Can we convert string to XML in Java?

Document convertStringToDocument(String xmlStr) : This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion.

How do you write data to XML file in Java?

Write XML to a file Steps to create and write XML to a file. Create a Document doc . Create XML elements, attributes, etc., and append to the Document doc . Create a Transformer to write the Document doc to an OutputStream .


2 Answers

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.

like image 128
Jayendra Avatar answered Sep 21 '22 06:09

Jayendra


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); } 
like image 39
i100 Avatar answered Sep 21 '22 06:09

i100