【问题标题】:Is there a generic way of reading complex XML using SaxParser?是否有使用 SaxParser 读取复杂 XML 的通用方法?
【发布时间】:2022-06-20 20:58:44
【问题描述】:

我正在使用 SaxParser 读取大型复杂 XML 文件。我不希望创建模型类,因为我不知道将在 XML 中出现的确切数据,所以我试图找出是否存在使用某种上下文读取 XML 数据的通用方法。

我使用 Jackson 对 JSON 使用了类似的方法,这对我来说效果很好。由于我是 Sax Parser 的新手,我无法完全理解如何实现相同的目标。对于复杂的内在价值,我无法建立父子关系,也无法建立标签和属性之间的关系。

以下是我目前的代码:

ContextNode 我的通用类使用父子关系存储所有 XML 信息。

@Getter
@Setter
@ToString
@NoArgsConstructor
public class ContextNode {
    protected String name;
    protected String value;
    protected ArrayList<ContextNode> children = new ArrayList<>();
    protected ContextNode parent;

    //Constructor 1: To store the simple field information.
    public ContextNode(final String name, final String value) {
        this.name = name;
        this.value = value;
    }

    //Constructor 2: To store the complex field which has inner elements.
    public ContextNode(final ContextNode parent, final String name, final String value) {
        this(name, value);
        this.parent = parent;
    }

以下是我在EventReader.class 中使用 SAX 解析 XML 的方法

public class EventReader{
//Method to read XML events and create pre-hash string from it.
public static void xmlParser(final InputStream xmlStream) {
    final SAXParserFactory factory = SAXParserFactory.newInstance();

    try {
        final SAXParser saxParser = factory.newSAXParser();
        final SaxHandler handler = new SaxHandler();
        saxParser.parse(xmlStream, handler);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
}
}

以下是我的SaxHandler:

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

import java.util.HashMap;

public class SaxHandler extends DefaultHandler {

    private final List<String> XML_IGNORE_FIELDS = Arrays.asList("person:personDocument","DocumentBody","DocumentList");
    private final List<String> EVENT_TYPES = Arrays.asList("person");
    private Map<String, String> XML_NAMESPACES = null;
    private ContextNode contextNode = null;
    private StringBuilder currentValue = new StringBuilder();

    @Override
    public void startDocument() {
        ConstantEventInfo.XML_NAMESPACES = new HashMap<>();
    }

    @Override
    public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) {
        //For every new element in XML reset the StringBuilder.
        currentValue.setLength(0);

        if (qName.equalsIgnoreCase("person:personDocument")) {
            // Add the attributes and name-spaces to Map
            for (int att = 0; att < attributes.getLength(); att++) {

                if (attributes.getQName(att).contains(":")) {
                    //Find all Namespaces within the XML Header information and save it to the Map for future use.
                    XML_NAMESPACES.put(attributes.getQName(att).substring(attributes.getQName(att).indexOf(":") + 1), attributes.getValue(att));
                } else {
                    //Find all other attributes within XML and store this information within Map.
                    XML_NAMESPACES.put(attributes.getQName(att), attributes.getValue(att));
                }
            }
        } else if (EVENT_TYPES.contains(qName)) {
            contextNode = new ContextNode("type", qName);
        }
    }

    @Override
    public void characters(char ch[], int start, int length) {
        currentValue.append(ch, start, length);
    }

    @Override
    public void endElement(final String uri, final String localName, final String qName) {
        if (!XML_IGNORE_FIELDS.contains(qName)) {
            if (!EVENT_TYPES.contains(qName)) {
                System.out.println("QName : " + qName + " Value : " + currentValue);
                contextNode.children.add(new ContextNode(qName, currentValue.toString()));
            }
        }
    }

    @Override
    public void endDocument() {
        System.out.println(contextNode.getChildren().toString());
        System.out.println("End of Document");
    }
}

以下是我的TestCase,它将调用方法xmlParser

@Test
public void xmlReader() throws Exception {
    final InputStream xmlStream = getClass().getResourceAsStream("/xmlFileContents.xml");
    EventReader.xmlParser(xmlStream);
}

以下是我需要使用通用方法读取的 XML:

<?xml version="1.0" ?>
<person:personDocument xmlns:person="https://example.com" schemaVersion="1.2" creationDate="2020-03-03T13:07:51.709Z">
<DocumentBody>
    <DocumentList>
        <Person>
            <bithTime>2020-03-04T11:00:30.000+01:00</bithTime>
            <name>Batman</name>
            <Place>London</Place>
            <hobbies>
                <hobby>painting</hobby>
                <hobby>football</hobby>
            </hobbies>
            <jogging distance="10.3">daily</jogging>
            <purpose2>
                <id>1</id>
                <purpose>Dont know</purpose>
            </purpose2>
        </Person>
    </DocumentList>
</DocumentBody>
</person:personDocument>

【问题讨论】:

  • 您没有发布EventReader。无论如何,tl;博士。您说I am unable to establish a parent-child relationship,也许您应该将元素推送到startElement 上的Stack 并弹出任何新的startElement,并将弹出的元素指定为当前元素的父元素。
  • @PeterMmm 非常感谢您的回复。 EventReader 类包含方法 xmlParser 方法,我在这里发布。

标签: java xml sax saxparser


【解决方案1】:

提供答案,因为它可能对将来的某人有所帮助:

首先我们需要创建一个类ContextNode来保存信息:

@Getter
@Setter
public class ContextNode {
    protected String name;
    protected String value;
    protected ArrayList<ContextNode> attributes = new ArrayList<>();
    protected ArrayList<ContextNode> children = new ArrayList<>();
    protected ContextNode parent;
    protected Map<String, String> namespaces;

    public ContextNode(final ContextNode parent, final String name, final String value) {
        this.parent = parent;
        this.name = name;
        this.value = value;
        this.namespaces = parent.namespaces;
    }
   
    public ContextNode(final Map<String, String> namespaces) {
        this.namespaces = namespaces;
    }

    public ContextNode(final Map<String, String> namespaces) {
        this.namespaces = namespaces;
    }
}

然后我们可以读取XML并将信息存储在上下文节点中:

import lombok.Getter;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

import java.security.NoSuchAlgorithmException;
import java.util.*;

public class SaxHandler extends DefaultHandler {

    //Variables needed to store the required information during the parsing of the XML document.
    private final Deque<String> path = new ArrayDeque<>();
    private final StringBuilder currentValue = new StringBuilder();
    private ContextNode currentNode = null;
    private ContextNode rootNode = null;
    private Map<String, String> currentAttributes;
    private final HashMap<String, String> contextHeader = new HashMap<>();

    @Override
    public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) {
        //Put every XML tag within the stack at the beginning of the XML tag.
        path.push(qName);

        //Reset attributes for every element
        currentAttributes = new HashMap<>();

        //Get the path from Deque as / separated values.
        final String p = path();

        //If the XML tag contains the Namespaces or attributes then add to respective Namespaces Map or Attributes Map.
        if (attributes.getLength() > 0) {
            //Loop over every attribute and add them to respective Map.
            for (int att = 0; att < attributes.getLength(); att++) {
                //If the attributes contain the : then consider them as namespaces.
                if (attributes.getQName(att).contains(":") && attributes.getQName(att).startsWith("xmlns:")) {
                    contextHeader.put(attributes.getQName(att).substring(attributes.getQName(att).indexOf(":") + 1), attributes.getValue(att));
                } else {
                    currentAttributes.put(attributes.getQName(att), attributes.getValue(att).trim());
                }
            }
        }

        if (rootNode == null) {
            rootNode = new ContextNode(contextHeader);
            currentNode = rootNode;
            rootNode.children.add(new ContextNode(rootNode, "type", qName));
        } else if (currentNode != null) {
            ContextNode n = new ContextNode(currentNode, qName, (String) null);
            currentNode.children.add(n);
            currentNode = n;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) {
        currentValue.append(ch, start, length);
    }

    @Override
    public void endElement(final String uri, final String localName, final String qName) {
        try {
            System.out.println("completed reading");
            System.out.println(rootNode);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }


        rootNode = null;
        

        //At the end of the XML element tag reset the value for next element.
        currentValue.setLength(0);

        //After completing the particular element reading, remove that element from the stack.
        path.pop();
    }

    private String path() {
        return String.join("/", this.path);
    }
}


您可能需要根据您的特定要求进行一些额外的更改。这只是一个提供一些想法的示例。

【讨论】:

    猜你喜欢
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多