这是indexloc提供的服务,不要输入任何密码
Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion xml-3/src/test/java/com/baeldung/xml/XmlDocumentUnitTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,17 @@
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;

import static org.junit.jupiter.api.Assertions.*;

public class XmlDocumentUnitTest {

@Test
public void givenXmlString_whenConvertToDocument_thenSuccess() throws Exception {
public void givenXmlString_whenConvertToDocumentViaString_thenSuccess() throws Exception {
String xmlString = "<root><child>Example</child></root>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Expand Down Expand Up @@ -64,4 +67,41 @@ public void givenInvalidXmlString_whenConvertToDocument_thenThrowException() thr
builder.parse(new InputSource(new StringReader(invalidXmlString)));
});
}

@Test
public void givenXmlString_whenConvertToDocumentViaCharStream_thenSuccess() throws Exception {
String xmlString = "<posts><post postId='1'><title>Example Post</title><author>John Doe</author></post></posts>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

InputSource inputSource = new InputSource(new StringReader(xmlString));
Document document = builder.parse(inputSource);

assertNotNull(document);
assertEquals("posts", document.getDocumentElement().getNodeName());

Element rootElement = document.getDocumentElement();
var childElements = rootElement.getElementsByTagName("post");
assertNotNull(childElements);
assertEquals(1, childElements.getLength());
}

@Test
public void givenXmlString_whenConvertToDocumentViaByteArray_thenSuccess() throws Exception {
String xmlString = "<posts><post postId='1'><title>Example Post</title><author>John Doe</author></post></posts>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

InputStream inputStream = new ByteArrayInputStream(xmlString.getBytes(StandardCharsets.UTF_8));
Document document = builder.parse(inputStream);

assertNotNull(document);
assertEquals("posts", document.getDocumentElement().getNodeName());

Element rootElement = document.getDocumentElement();
var childElements = rootElement.getElementsByTagName("post");
assertNotNull(childElements);
assertEquals(1, childElements.getLength());
}

}