Author

Output Document to String

The following code wraps StringWriter to StreamResult . In this way we can convert DOM document to a string.

import java.io.StringWriter; //from j a v a2s.co m import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; public class Main < private static void toString(Document newDoc) throws Exception< DOMSource domSource = new DOMSource(newDoc); Transformer transformer = TransformerFactory.newInstance().newTransformer(); StringWriter sw = new StringWriter(); StreamResult sr = new StreamResult(sw); transformer.transform(domSource, sr); System.out.println(sw.toString()); > public static void main(String[] args) throws Exception < DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); Document newDoc = domBuilder.newDocument(); Element rootElement = newDoc.createElement("parent"); newDoc.appendChild(rootElement); toString(newDoc); > > 

Next chapter.

What you will learn in the next chapter:

Источник

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

Читайте также:  Как сделать слева css

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

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.

  1. 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.
  2. 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.

Источник

How to convert String to org.w3c.dom.Document

send pies

posted 14 years ago

  • Report post to moderator
  • How to convert String to org.w3c.dom.Document

    Marshal

    send pies

    posted 14 years ago

    • 1
  • Report post to moderator
  • Sheriff

    Chrome

    send pies

    posted 14 years ago

  • Report post to moderator
  • SCJP 1.4 — SCJP 6 — SCWCD 5 — OCEEJBD 6 — OCEJPAD 6
    How To Ask Questions How To Answer Questions

    send pies

    posted 10 years ago

    • 1
  • Report post to moderator
  • To convert String to Dom/Document object

    and if you have input stream that you can directly transform stram to document object

    Источник

    String to org.w3c.dom.Document

    parse возвращает null, т.е. объект document создается но он пустой.
    Я так подозреваю, что xml невалидный потому не хочет его парсить. Как можно распарсить подобное?

    cast to SVGSVGElement from org.w3c.dom.Element fails
    Seriously, if I cast like this: (SVGSVGElement).

    Java String convert to Document
    Всем привет! Ребят, подскажите как быть.. Задача такая.. Пишу клиет веб сервиса центробанка.

    Как удалить узел используя DOM DOCUMENT?
    Как убрать узел используя DOM DOCUMENT в HTML и заместить его обычным текстом или другим узлом.

    Эксперт Java

    так DOM парсер, насколько я помню, по дефолту не проверяет схему xml документа, а парсит именно по нодам. Тип, если синтаксис правильный, а он правильный, то должно читать

    Лучший ответ

    Сообщение было отмечено iSmokeJC как решение

    Решение

    Я просто кусок идиота! Писал вечером. Ошибка была не в парсинге. Ошибка была при добавлении элемента в документ при вызове appendChild.

    builder = factory.newDocumentBuilder(); xmlStr = xmlStr.replaceAll("\n|\r|\t",""); StringReader reader = new StringReader(xmlStr); InputSource source = new InputSource(reader); Document docHeader = builder.parse(source); Node tmpNode = doc.importNode(docHeader.getDocumentElement(), true); doc.getDocumentElement().appendChild(tmpNode);

    Написать скрипт, рекурсивно обходящий дерево DOM страницы dom.html, начиная от корня DOM
    Написать скрипт на языке JavaScript, рекурсивно обходящий дерево DOM страницы dom.html, начиная от.

    Как это работает (function(document) <.>)(document);?
    Добрый день! Нашёл замечательный скрипт menu effects. Хочу прикрутить к своему сайту. Во всех.

    Источник

    Оцените статью