如何使用 Java 和 XmlSchema Core 解析 XSD 并读取所有复杂元素及其子元素

如何解决如何使用 Java 和 XmlSchema Core 解析 XSD 并读取所有复杂元素及其子元素

我正在使用 Apache XmlSchema Core 库来解析 XSD 文件获取所有元素及其子类型(数据类型、maxOccurs 等)。我正在关注文档 Apache XML SCHEMA CORE 并尝试去做。但是在导航到某个点后,我有点困惑。有人可以指导我如何遍历我的 XSD 文件获取所有元素及其子元素以及相关信息吗?

我能够在我的 schema 元素中获取所有 XSD 信息我只想知道如何从我的根 RootFood 访问子元素并获取其相关信息。任何帮助将不胜感激。

我试图继续,这是我目前所拥有的: 元素 RootFood 属于类 XmlSchemaGroupParticle 的实例。我试图调试代码以找到与我的 rootParticles 关联的元素,它有一个名为 items 的字段,其中我有我的 food 元素 items->[0]->namedDelegate->qName->localPart 但是当我尝试在 GET添加 rootParticles 方法获取 items 那么没有这样的方法

XmlSchemaParticle 扩展了以下类:XmlSchemaAnnotatedXmlSchemaObject,并实现了接口 XmlSchemaObjectBase,但它们都没有名为 Items 的字段。>

以下是我到目前为止的 Java 代码,我尝试了几件事:

public class XMLSchemaCore {

    public static void main(String[] args) throws URISyntaxException,FileNotFoundException,UnsupportedEncodingException {
            String xsdpath = Paths.get(XMLSchemaCore.class.getClassLoader().getResource("test.xsd").toURI()).toFile().getAbsolutePath();
            String filePath = Path.of(xsdpath).toString();

            InputStream is = new FileInputStream(filePath);
            XmlSchemaCollection schemaCol = new XmlSchemaCollection();

            // Schema contain the complete XSD content which needs to be parsed
            XmlSchema schema = schemaCol.read(new StreamSource(is));
            // schema.write(System.out);
            for (Map.Entry<QName,XmlSchemaElement> entry: schema.getElements().entrySet()) {
                // Root element and its contents
                QName parentElementName = entry.getKey();
                XmlSchemaElement parentElementValues = entry.getValue();

                // Get the elements based on the Root element
                XmlSchemaElement root = schema.getElementByName(parentElementName);

                // Get the type of the root element
                XmlSchemaType type = root != null ? root.getSchemaType() : null;

                // Check if the root element is of Complex type
                if (type instanceof XmlSchemaComplexType) {
                    // Get the Particles associated with the element
                    XmlSchemaParticle rootParticles = ((XmlSchemaComplexType) type).getParticle();

                    // Check particle belongs to which type
                    if (rootParticles instanceof XmlSchemaAny) {
                        System.out.println("Any Schema Type");

                    } else if (rootParticles instanceof XmlSchemaElement) {
                        System.out.println("Element Schema Type");

                    } else if (rootParticles instanceof XmlSchemaGroupParticle) {
                        System.out.println("Group Schema Type");
                        System.out.println(rootParticles);
                        System.out.println(rootParticles);

                    } else if (rootParticles instanceof XmlSchemaGroupRef) {
                        System.out.println("Group Ref Schema Type");

                    }
                }
            }

        }

}

以下是我拥有的 XSD 文件

<xs:schema attributeFormDefault="unqualified"
    elementFormDefault="qualified"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="RootFood">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="food">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element type="xs:string" name="name" />
                            <xs:element type="xs:string" name="price" />
                            <xs:element type="xs:string" name="description" />
                            <xs:element type="xs:short" name="calories" />
                            <xs:element name="ingredients">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element type="xs:string" name="ingredient"
                                            maxOccurs="unbounded" minOccurs="0" />
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

enter image description here

解决方法

在尝试了很多事情之后,我能够使代码正常工作。在此处发布代码,因为它可能对计划使用 Apache XMLSchema Core Library for XML/XSD parsing 的人有所帮助。我知道这有多令人沮丧,因为我们在互联网上没有关于这个解析库的一些好的例子。希望这会有所帮助。

基本上,这段代码将解析整个 XSD 文件并根据其父元素和子元素将元素存储在 HashMap 中。您可以获得任何 XSD 元素的父级,也可以获得与子级相关的信息,例如其父级等。检查 XmlSchemaElement 以获取有关每个子级信息的更多详细信息:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;

import org.apache.ws.commons.schema.XmlSchema;
import org.apache.ws.commons.schema.XmlSchemaAny;
import org.apache.ws.commons.schema.XmlSchemaCollection;
import org.apache.ws.commons.schema.XmlSchemaComplexType;
import org.apache.ws.commons.schema.XmlSchemaElement;
import org.apache.ws.commons.schema.XmlSchemaGroupRef;
import org.apache.ws.commons.schema.XmlSchemaParticle;
import org.apache.ws.commons.schema.XmlSchemaSequence;
import org.apache.ws.commons.schema.XmlSchemaSequenceMember;
import org.apache.ws.commons.schema.XmlSchemaType;

public class XMLSchemaCore {

    private static XmlSchemaCollection xmlSchemaCollection;
    private static Map<QName,List<XmlSchemaElement>> xsdElements = new HashMap<QName,List<XmlSchemaElement>>();
    private static List<XmlSchemaElement> schemaElements = new ArrayList<XmlSchemaElement>();

    public static void main(String[] args) throws URISyntaxException,FileNotFoundException,UnsupportedEncodingException {
        // Path for the file which is stored within the Resource folder
        String xsdPath = Paths.get(XMLSchemaCore.class.getClassLoader().getResource("test.xsd").toURI()).toFile().getAbsolutePath();
        String filePath = Path.of(xsdPath).toString();

        InputStream is = new FileInputStream(filePath);
        xmlSchemaCollection = new XmlSchemaCollection();

        // Schema contain the complete XSD content which needs to be parsed
        XmlSchema schema = xmlSchemaCollection.read(new StreamSource(is));
        // schema.write(System.out);

        // Get the root element from XSD
        Map.Entry<QName,XmlSchemaElement> entry = schema.getElements().entrySet().iterator().next();
        QName rootElement = entry.getKey();

        // Get all the elements based on the parent element
        XmlSchemaElement childElement = xmlSchemaCollection.getElementByQName(rootElement);

        // Call method to get all the child elements
        getChildElementNames(childElement);

        String element = "" + xsdElements.entrySet().stream().map(e -> e.getKey() + " -- " + String.join(",",e.getValue().stream().map(v -> v
                            .getQName().toString()).collect(Collectors.toList()))).collect(Collectors.toList());

        System.out.println(element);
    }

    // Method to check for the child elements and return list
    private static void getChildElementNames(XmlSchemaElement element) {

        // Get the type of the element
        XmlSchemaType elementType = element != null ? element.getSchemaType() : null;

        // Confirm if the element is of Complex type
        if (elementType instanceof XmlSchemaComplexType) {
            // Get all particles associated with that element Type
            XmlSchemaParticle allParticles = ((XmlSchemaComplexType) elementType).getParticle();

            // Check particle belongs to which type
            if (allParticles instanceof XmlSchemaAny) {
                System.out.println("Any Schema Type");

            } else if (allParticles instanceof XmlSchemaElement) {
                System.out.println("Element Schema Type");

            } else if (allParticles instanceof XmlSchemaSequence) {
                // System.out.println("Sequence Schema Type");
                final XmlSchemaSequence xmlSchemaSequence = (XmlSchemaSequence) allParticles;
                final List<XmlSchemaSequenceMember> items = xmlSchemaSequence.getItems();
                items.forEach((item) -> {
                    XmlSchemaElement itemElements = (XmlSchemaElement) item;
                    schemaElements.add(itemElements);
                    // System.out.println(" Parent : " + element.getQName() + " -- Child : " +
                    // itemElements.getQName());
                    //Call the method to add the current element as child
                    addChild(element.getQName(),itemElements);
                    // Call method recursively to get all subsequent element
                    getChildElementNames(itemElements);
                    schemaElements = new ArrayList<XmlSchemaElement>();
                });

            } else if (allParticles instanceof XmlSchemaGroupRef) {

            }
        }
    }

    // Add child elements based on its parent
    public static void addChild(QName qName,XmlSchemaElement child) {
        List<XmlSchemaElement> values = xsdElements.get(qName);
        if (values == null) {
            values = new ArrayList<XmlSchemaElement>();
        }
        values.add(child);
        xsdElements.put(qName,values);
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?