|
| 1 | +package org.javawebstack.abstractdata.xml; |
| 2 | + |
| 3 | +import org.w3c.dom.*; |
| 4 | +import org.xml.sax.SAXException; |
| 5 | + |
| 6 | +import javax.xml.parsers.DocumentBuilderFactory; |
| 7 | +import javax.xml.parsers.ParserConfigurationException; |
| 8 | +import java.io.ByteArrayInputStream; |
| 9 | +import java.io.IOException; |
| 10 | +import java.nio.charset.StandardCharsets; |
| 11 | + |
| 12 | +/* |
| 13 | +This is a temporary implementation using Java's built-in xml implementation |
| 14 | + */ |
| 15 | +public class LegacyXMLParser { |
| 16 | + |
| 17 | + @Deprecated |
| 18 | + protected static XMLElement parse(String s) { |
| 19 | + try { |
| 20 | + Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8))); |
| 21 | + return convert(document.getDocumentElement()); |
| 22 | + } catch (SAXException | IOException | ParserConfigurationException e) { |
| 23 | + throw new RuntimeException(e); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + private static XMLElement convert(Element element) { |
| 28 | + String tag = element.getTagName(); |
| 29 | + XMLElement e = new XMLElement(tag); |
| 30 | + NamedNodeMap attrNodeMap = element.getAttributes(); |
| 31 | + for(int i=0; i<attrNodeMap.getLength(); i++) { |
| 32 | + String name = attrNodeMap.item(i).getNodeName(); |
| 33 | + String value = ((Attr) attrNodeMap.item(i)).getValue(); |
| 34 | + e.attr(name, value); |
| 35 | + } |
| 36 | + NodeList nodeList = element.getChildNodes(); |
| 37 | + for(int i=0; i<nodeList.getLength(); i++) { |
| 38 | + Node node = nodeList.item(i); |
| 39 | + switch (node.getNodeType()) { |
| 40 | + case Node.ATTRIBUTE_NODE: { |
| 41 | + Attr attr = (Attr) node; |
| 42 | + e.attr(attr.getName(), attr.getValue()); |
| 43 | + break; |
| 44 | + } |
| 45 | + case Node.ELEMENT_NODE: { |
| 46 | + e.child(convert((Element) node)); |
| 47 | + break; |
| 48 | + } |
| 49 | + case Node.CDATA_SECTION_NODE: |
| 50 | + case Node.TEXT_NODE: { |
| 51 | + e.child(new XMLTextNode(((Text) node).getData())); |
| 52 | + break; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + return e; |
| 57 | + } |
| 58 | + |
| 59 | +} |
0 commit comments