/
NikolayIvkin
/
tutorials1
Обзор
Документация
Войти
/
NikolayIvkin
/
tutorials1
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
xml-2/src/test/java/com/baeldung/xml/xml2document/XMLStringToDocumentObjectUnitTest.java
37 строк
1 KB
Jonathan Cook
BAEL-7864 - How to convert org.w3c.dom.Document to String in Java (#16713)
24 май 2024, 19:24
Не верифицирован
24 май 2024, 19:24
9d617aa
Код
Авторство
О чём код?
package com.baeldung.xml.xml2document; import org.junit.Test; import org.w3c.dom.*; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; import java.io.StringReader; import static org.junit.Assert.assertEquals; public class XMLStringToDocumentObjectUnitTest { @Test public void givenValidXMLString_whenParsing_thenDocumentIsCorrect() throws ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); String xmlString = "<root><element>XML Parsing Example</element></root>"; InputSource is = new InputSource(new StringReader(xmlString)); Document xmlDoc = null; try { xmlDoc = builder.parse(is); } catch (SAXException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } assertEquals("root", xmlDoc.getDocumentElement().getNodeName()); assertEquals("element", xmlDoc.getDocumentElement().getElementsByTagName("element").item(0).getNodeName()); assertEquals("XML Parsing Example", xmlDoc.getDocumentElement().getElementsByTagName("element").item(0).getTextContent()); } }