01: /*
02: * Copyright (C) 2004, 2005 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 07. March 2004 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.io.xml;
13:
14: import com.thoughtworks.xstream.io.HierarchicalStreamReader;
15:
16: import org.w3c.dom.Document;
17: import org.w3c.dom.Element;
18:
19: import javax.xml.parsers.DocumentBuilder;
20: import javax.xml.parsers.DocumentBuilderFactory;
21:
22: import java.io.ByteArrayInputStream;
23: import java.util.HashMap;
24: import java.util.Map;
25:
26: public class DomReaderTest extends AbstractXMLReaderTest {
27:
28: // factory method
29: protected HierarchicalStreamReader createReader(String xml)
30: throws Exception {
31: return new DomReader(buildDocument(xml));
32: }
33:
34: private Document buildDocument(String xml) throws Exception {
35: DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
36: .newInstance();
37: DocumentBuilder documentBuilder = documentBuilderFactory
38: .newDocumentBuilder();
39: ByteArrayInputStream inputStream = new ByteArrayInputStream(xml
40: .getBytes());
41: Document document = documentBuilder.parse(inputStream);
42: return document;
43: }
44:
45: public void testCanReadFromElementOfLargerDocument()
46: throws Exception {
47: Document document = buildDocument("" + "<big>" + " <small>"
48: + " <tiny/>" + " </small>" + " <small-two>"
49: + " </small-two>" + "</big>");
50: Element small = (Element) document.getDocumentElement()
51: .getElementsByTagName("small").item(0);
52:
53: HierarchicalStreamReader xmlReader = new DomReader(small);
54: assertEquals("small", xmlReader.getNodeName());
55: xmlReader.moveDown();
56: assertEquals("tiny", xmlReader.getNodeName());
57: }
58:
59: public void testExposesAttributesKeysAndValuesByIndex()
60: throws Exception {
61:
62: // overrides test in superclass, because DOM does not retain order of actualAttributes.
63:
64: HierarchicalStreamReader xmlReader = createReader("<node hello='world' a='b' c='d'><empty/></node>");
65:
66: assertEquals(3, xmlReader.getAttributeCount());
67:
68: Map expectedAttributes = new HashMap();
69: expectedAttributes.put("hello", "world");
70: expectedAttributes.put("a", "b");
71: expectedAttributes.put("c", "d");
72:
73: Map actualAttributes = new HashMap();
74: for (int i = 0; i < xmlReader.getAttributeCount(); i++) {
75: String name = xmlReader.getAttributeName(i);
76: String value = xmlReader.getAttribute(i);
77: actualAttributes.put(name, value);
78: }
79:
80: assertEquals(expectedAttributes, actualAttributes);
81:
82: xmlReader.moveDown();
83: assertEquals("empty", xmlReader.getNodeName());
84: assertEquals(0, xmlReader.getAttributeCount());
85: }
86:
87: }
|