- Java Преобразует строку в XML – документ и XML-документ в строку
- Читайте ещё по теме:
- Java Convert String to XML DOM Example
- Java Convert String to XML Document and XML Document to String
- Как преобразовать строку в XML Document. Создаем String из Document
- Из String в XML Document и наоборот
- Конвертация в String из XML Document и наоборот на примере
- How to convert string to xml file in java
Java Преобразует строку в XML – документ и XML-документ в строку
Строка в XML Java-программе. Пример XML-документа для построения Java-программы. TransformerFactory преобразование, DocumentBuilderFactory, разбор DocumentBuilder.
Иногда при программировании на java мы получаем Строку , которая на самом деле является XML, и для ее обработки нам нужно преобразовать ее в XML-документ ( org.w3c.dom.Документ ). Также для целей отладки или для отправки в какую-либо другую функцию нам может потребоваться преобразовать объект документа в строку.
Здесь я предоставляю две полезные функции.
- Документ convertStringToDocument(Строка xmlStr) : Этот метод примет входные данные в виде строки, а затем преобразует их в документ DOM и вернет его. Для этого преобразования мы будем использовать Источник ввода и средство чтения строк.
- Строка convertDocumentToString(Документ doc) : Этот метод примет ввод в качестве документа и преобразует его в строку. Для этой цели мы будем использовать Transformer , StringWriter и StreamResult .
package com.journaldev.xml; import java.io.StringReader; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.xml.sax.InputSource; public class StringToDocumentToString < public static void main(String[] args) < final String xmlStr 1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+ ""; Document doc = convertStringToDocument(xmlStr); String str = convertDocumentToString(doc); System.out.println(str); > private static String convertDocumentToString(Document doc) < TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; try < transformer = tf.newTransformer(); // below code to remove XML declaration // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); String output = writer.getBuffer().toString(); return output; >catch (TransformerException e) < e.printStackTrace(); >return null; > private static Document convertStringToDocument(String xmlStr) < DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try < builder = factory.newDocumentBuilder(); Document doc = builder.parse( new InputSource( new StringReader( xmlStr ) ) ); return doc; >catch (Exception e) < e.printStackTrace(); >return null; > > Pankaj 25 \n"+ "Developer Male
Когда мы запускаем вышеуказанную программу, мы получаем тот же вывод строки, который мы использовали для создания документа DOM.
Вы можете использовать replaceAll(«\n|\r»,»») , чтобы удалить новые символы строки из строки и получить ее в компактном формате.
Читайте ещё по теме:
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.
Java Convert String to XML Document and XML Document to String
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
- 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.
- String convertDocumentToString(Document doc) : This method will take input as Document and convert it to String. We will use Transformer , StringWriter and StreamResult for this purpose.
package com.journaldev.xml; import java.io.StringReader; import java.io.StringWriter; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.xml.sax.InputSource; public class StringToDocumentToString < public static void main(String[] args) < final String xmlStr = "\n"+ "DeveloperMale "; Document doc = convertStringToDocument(xmlStr); String str = convertDocumentToString(doc); System.out.println(str); > private static String convertDocumentToString(Document doc) < TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; try < transformer = tf.newTransformer(); // below code to remove XML declaration // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); String output = writer.getBuffer().toString(); return output; >catch (TransformerException e) < e.printStackTrace(); >return null; > private static Document convertStringToDocument(String xmlStr) < DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try < builder = factory.newDocumentBuilder(); Document doc = builder.parse( new InputSource( new StringReader( xmlStr ) ) ); return doc; >catch (Exception e) < e.printStackTrace(); >return null; > >
When we run above program, we get the same String output that we used to create DOM Document.
You can use replaceAll("\n|\r", "") to remove new line characters from String and get it in compact format.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Как преобразовать строку в XML Document. Создаем String из Document
В этой статье мы познакомимся с простым способом преобразования строки в объект XML Document и обратной конвертации XML Document в строку. А также разберем зачем это нужно.
Из String в XML Document и наоборот
Программируя на Java часто приходится иметь дело со строками, которые содержат в себе XML разметку. Такие объекты нужно как-то обрабатывать. Для этого нам нужно преобразовать (конвертировать) такую строку c XML в объект Document ( org.w3c.dom.Document ). Похожая задача конвертации стоит во время отладки, когда нам потребуется преобразовать XML Document в объект String.
В этой статье мы разбирались как сделать красивый и читабельный вывод неотформатированной строки с XML разметкой. В этой статье нас больше интересует правильный способ преобразования между String и объектом Document.
Конвертация в String из XML Document и наоборот на примере
Напишем 2 метода для конвертации и обратного преобразования XML и String:
- Метод stringToDocument(String xmlString) принимает на вход строку из XML разметкой, а затем парсит ее и возвращает в виде Document DOM. Мы будем использовать InputSource и StringReader для этого.
- Метод documentToString(Document document) принимает на вход Document и преобразовывает его в объект String. Для этого используются классы Transformer , StringWriter и StreamResult пакета javax.xml.transform .
Напишем класс DocumentToStringConverter и реализуем этим методы:
How to convert string to xml file in java
posted 12 years ago
- 1
Hi friends
I am getting the response from webservice as string below content .can anyboy tell how to convert string to xml file in java
posted 12 years ago
posted 11 years ago
Exact output should like as below..
posted 11 years ago
pawan chopra wrote: Try this one :
In which drive(C) or drrive (D), it will save the xmlFileName.xml, where you have mentioned that.
posted 11 years ago
I have tried the code which you have suggested. My question is, after converting the xml string to XML file say A.xml.
I want to read the A.XML file and append the data (data is in xml string) to the A.XML file.
posted 11 years ago
I have stored the xml file ( xmlfilename.xml) in different name (I have changed the xml file xmlfilename.xml to books.xml) in my program.
Now, I have another string which contains the XML tags needs to be appended to the existing file books.xml file..
posted 11 years ago
Thanks for your response.. I have found the solution.
posted 11 years ago
Thanks for your response.. I have found the solution.
Can you please post your final code here so that we can have a look because one thing that is not clear is that where you have mentioned the path in the code from where it will pick up the college.xml. just like that .
and where you have mentioned the path of the final xml that is created in which drive and under which directory.
It will be graet if you can post your full and final solution that will be a great help. thanks in advance.
posted 11 years ago
Saral Saxena wrote:
Can you please post your final code here so that we can have a look because one thing that is not clear is that where you have mentioned the path in the code from where it will pick up the college.xml. just like that . . and where you have mentioned the path of the final xml that is created in which drive and under which directory.
The path if not specified will take the folder from where the execution is done. Try below code in your desktop.