- How to read XML values using string methods of Java
- Java Convert String to XML DOM Example
- How to parse a String containing XML in Java and retrieve the value of the root node?
- 6 Answers 6
- Convert the string content into an XMLStreamReader
- 3 Answers 3
- Related
- Hot Network Questions
- Subscribe to RSS
- Java — how to convert a XML string into an XML file?
- 4 Answers 4
How to read XML values using string methods of Java
Note that tags are not going to be repeated. The above contents are stored in a String. I want to write a java method which does something like this :
tagvalue = getvalue() for example tagvalue=getvalye(Name)
Also, I want a method which will return the root tag (1st Tag from the string) i.e It should return «Test» . I know Java parser and DOM can do this task but I don’t want to use them. Can I simply do it by string manipulation method? or some other method? The solution am trying is as follows :
//Method Call String tag_value = getvalue(databuffer,"Name"); //Method private String getvalue(String Content, String Tagname) < if (Content.contains("")) < if(Content.contains(""+Tagname+">")) < //How do I get Tag value here? return Tagvalue; >> >
//method private String getvalue(String Content, String Tagname) < //XYZ int Starttag = Content.indexOf("");//Returns 0 int Endtag = Content.indexOf(""+Tagname+">");//Returns 9 //How to find the total length of so that I can subtract it with the index of Endtag to get the value? return ; >
Can I get any help from anyone please? //I have updated my question for namespace in the the element name. Input file will look like the following
NOTE: I don’t know the namespace that is going to come? it might be ns or np. anything..how to handle that? One thing i know is delimiter will be «:» Is it possible to use string methods to simply ignore namespace in the element name to get the element value in the following logic? Method call: String elementvalue = getElementvalue(databuffer,»Name») Method:
public String getvalue(String buffer, String tagname) < String startTag, endTag,elementdata = null; int startposition,endposition; try < startTag = ""; endTag = ""+ tagname + ">"; startposition = buffer.indexOf(startTag); startposition = startposition + startTag.length(); endposition = buffer.indexOf(endTag); elementdata = buffer.substring(startposition, endposition); > return elementdata; >
Java Convert String to XML DOM Example
To convert XML string to XML Dom, we need the following classes:
- javax.xml.parsers.DocumentBuilder : Defines the API to obtain XML DOM Document instances from XML content from various input sources. These input sources are InputStreams, Files, URLs, and SAX InputSources.
- javax.xml.parsers.DocumentBuilderFactory : Defines a factory API that enables applications to obtain a parser ( DocumentBuilder ) that produces DOM object trees from XML content.
- org.w3c.dom.Document : It represents the entire XML DOM. Conceptually, it is the root of the document tree, and provides the access to the document’s data further down into the tree, through factory methods.
- java.io.StringReader : Create a stream from String content. DocumentBuilder uses this stream to read XML content for parsing.
import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class ConvertStringToXML < public static void main(String[] args) < final String xmlStr + " Lokesh Gupta" + " " + " " + " Brian Lara" + " " + " " + ""; //Use method to convert XML string content to XML Document object Document doc = convertStringToXMLDocument(xmlStr); //Verify XML document is build correctly System.out.println("Root Node : " + doc.getFirstChild().getNodeName()); NodeList nodeList = doc.getElementsByTagName("employee"); for (int itr = 0; itr < nodeList.getLength(); itr++) < Node node = nodeList.item(itr); System.out.println("\nNode Name : " + node.getNodeName()); if (node.getNodeType() == Node.ELEMENT_NODE) < Element eElement = (Element) node; System.out.println("Name: "+ eElement.getElementsByTagName("name").item(0).getTextContent()); System.out.println("Title: "+ eElement.getElementsByTagName("title").item(0).getTextContent()); >> > private static Document convertStringToXMLDocument(String xmlString) < //Parser that produces DOM object trees from XML content DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //API to obtain DOM Document instance DocumentBuilder builder = null; try < //Create DocumentBuilder with default configuration builder = factory.newDocumentBuilder(); //Parse the content to Document object Document doc = builder.parse(new InputSource(new StringReader(xmlString))); return doc; >catch (Exception e) < e.printStackTrace(); >return null; > >
Root Node : employees Node Name : employee Name: Lokesh Gupta Title: Author Node Name : employee Name: Brian Lara Title: Cricketer
2. Convert XML File to XML Document
To get the XML dom from XML file, instead of passing the XML string to DocumentBuilder, pass the file path to let the parser read the file content directly.
We have employees.xml file which has XML content, we will read to get XML document.
Lokesh Gupta Brian Lara
import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; public class StringtoXMLExample < public static void main(String[] args) < final String xmlFilePath = "employees.xml"; //Use method to convert XML string content to XML Document object Document doc = convertXMLFileToXMLDocument( xmlFilePath ); //Verify XML document is build correctly System.out.println(doc.getFirstChild().getNodeName()); >private static Document convertXMLFileToXMLDocument(String filePath) < //Parser that produces DOM object trees from XML content DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); //API to obtain DOM Document instance DocumentBuilder builder = null; try < //Create DocumentBuilder with default configuration builder = factory.newDocumentBuilder(); //Parse the content to Document object Document doc = builder.parse(new File(filePath)); return doc; >catch (Exception e) < e.printStackTrace(); >return null; > >
Drop me your questions in the comments section.
How to parse a String containing XML in Java and retrieve the value of the root node?
How can I get the String «Hello!» from the XML? It should be ridiculously easy but I am lost. The XML isn’t in a doc, it is simply a String.
6 Answers 6
String xml = "HELLO! "; org.jdom.input.SAXBuilder saxBuilder = new SAXBuilder(); try < org.jdom.Document doc = saxBuilder.build(new StringReader(xml)); String message = doc.getRootElement().getText(); System.out.println(message); >catch (JDOMException e) < // handle JDOMException >catch (IOException e) < // handle IOException >
Using the Xerces DOMParser :
String xml = "HELLO! "; DOMParser parser = new DOMParser(); try < parser.parse(new InputSource(new java.io.StringReader(xml))); Document doc = parser.getDocument(); String message = doc.getDocumentElement().getTextContent(); System.out.println(message); >catch (SAXException e) < // handle SAXException >catch (IOException e) < // handle IOException >
Using the JAXP interfaces:
String xml = "HELLO! "; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try < db = dbf.newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); try < Document doc = db.parse(is); String message = doc.getDocumentElement().getTextContent(); System.out.println(message); >catch (SAXException e) < // handle SAXException >catch (IOException e) < // handle IOException >> catch (ParserConfigurationException e1) < // handle ParserConfigurationException >
import java.io.IOException; import java.io.StringReader; import org.jdom2.Document; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; public class TestXml < public static void main(String[] args) < String xml = "
You could also use tools provided by the base JRE:
String msg = "HELLO! "; DocumentBuilder newDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document parse = newDocumentBuilder.parse(new ByteArrayInputStream(msg.getBytes())); System.out.println(parse.getFirstChild().getTextContent());
Off topic but DocumentBuilder.parse() only takes an InputStream. I just wanted to write the smallest amount of example code.
unfortunately, that smallest amount of example code is also grossly wrong. converting xml text to arbitrary bytes using the default platform encoding is a recipe for breaking said xml. as you can see in some of the other answers, you can use an InputSource to pass a Reader to DocumentBuilder.
You could do this with JAXB (an implementation is included in Java SE 6).
import java.io.StringReader; import javax.xml.bind.*; import javax.xml.transform.stream.StreamSource; public class Demo < public static void main(String[] args) throws Exception < String xmlString = "HELLO! "; JAXBContext jc = JAXBContext.newInstance(String.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); StreamSource xmlSource = new StreamSource(new StringReader(xmlString)); JAXBElement je = unmarshaller.unmarshal(xmlSource, String.class); System.out.println(je.getValue()); > >
Convert the string content into an XMLStreamReader
@ Jon Skeet -my mistake. My quick lookup showed couple of more classes with same name. (commons-io lib was one). My question was not useful ..
3 Answers 3
You can use XMLInputFactory.createXMLStreamReader , passing in a StringReader to wrap your string.
String text = "This is some XML "; Reader reader = new StringReader(text); XMLInputFactory factory = XMLInputFactory.newInstance(); // Or newFactory() XMLStreamReader xmlReader = factory.createXMLStreamReader(reader);
@userrg: There’s no need to do that for a StringReader . nor, I’d imagine, for an XMLStreamReader which is reading from a StringReader . There are no native handles to close.
I assume you want to read XML content from a String via an XMLStreamReader . You can do that like this:
public XMLStreamReader readXMLFromString(final String xmlContent)
//Intialize XMLInputFactory XMLInputFactory factory = XMLInputFactory.newInstance(); //Reading from xml file and creating XMLStreamReader XMLStreamReader reader = inputFactory.createXMLStreamReader(new FileInputStream( file)); String currentElement = ""; //Reading all the data while(reader.hasNext()) < int next = reader.next(); if(next == XMLStreamReader.START_ELEMENT) currentElement = reader.getLocalName(); //System.out.println(currentElement); >
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.20.43540
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Java — how to convert a XML string into an XML file?
I am wanting to convert a xml string to a xml file. I am getting a xml string as an out put and I have the following code so far:
public static void stringToDom(String xmlSource) throws SAXException, ParserConfigurationException, IOException < DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(xmlSource))); //return builder.parse(new InputSource(new StringReader(xmlSource))); >
However Im not too sure where I go from here. I am not creating the file anywhere, so how do I incorporate that into it? I am passing my xml string into xmlSource.
4 Answers 4
If you just want to put the content of a String in a file, it doesn’t really matter whether it is actually XML or not. You can skip the parsing (which is a relatively expensive operation) and just dump the String to file, like so:
public static void stringToDom(String xmlSource) throws IOException
If you want to be on the safe side and circumvent encoding issues, as pointed by Joachim, you would need parsing however. Since its good practice to never trust your inputs, this might be the preferable way. It would look like this:
public static void stringToDom(String xmlSource) throws SAXException, ParserConfigurationException, IOException < // Parse the given input DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(xmlSource))); // Write the parsed document to an xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("my-file.xml")); transformer.transform(source, result); >