我希望能够读取XML模式(即xsd),并从中了解当我浏览它时有效的属性,子元素,值.
例如,假设我有一个xsd,这个xml将验证:
<root>
<element-a type="something">
<element-b>blah</element-b>
<element-c>blahblah</element-c>
</element-a>
</root>
Run Code Online (Sandbox Code Playgroud)
我已经修改了几个库,我可以自信地将其<root>作为根元素.除此之外,我迷失了.
给定一个元素,我需要知道的要求或允许孩子叫什么元素,属性方面,选择等使用上面的例子我想知道,element-a有一个属性type,可能有孩子element-b和element-c......或必须有儿童element-b和element-c......或者必须有一个...你得到我希望的图片.
我看过很多库,比如XSOM,Eclipse XSD,Apache XmlSchema,发现它们都是很好的示例代码.我对互联网的搜索也没有成功.
有没有人知道一个很好的例子,甚至是一本书,它演示了如何通过XML模式并找出在经过验证的XML文档中给定点的有效选项?
澄清
我不打算验证文档,而是希望了解给定点的选项以帮助创建或编辑文档.如果我在一份文件中知道"我在这里",我想确定那时我能做些什么."插入元素A,B或C中的一个"或"附加属性'描述'".
这是一个很好的问题。虽然它很旧,但我没有找到可接受的答案。问题是,我所知道的现有库(XSOM、Apache XmlSchema)被设计为对象模型。实现者无意提供任何实用方法 \xe2\x80\x94 您应该考虑使用提供的对象模型自己实现它们。
\n\n让我们看看如何通过 Apache XmlSchema 来查询特定于上下文的元素。
\n\n您可以使用他们的教程作为起点。此外,Apache CFX 框架还提供了XmlSchemaUtils类以及许多方便的代码示例。
\n\n首先,阅读XmlSchemaCollection图书馆教程中所示的内容:
XmlSchemaCollection xmlSchemaCollection = new XmlSchemaCollection();\nxmlSchemaCollection.read(inputSource, new ValidationEventHandler());\nRun Code Online (Sandbox Code Playgroud)\n\n现在,XML Schema 定义了两种数据类型:
\n\n简单类型由类表示XmlSchemaSimpleType。处理它们很容易。阅读文档:https://ws.apache.org/commons/XmlSchema/apidocs/org/apache/ws/commons/schema/XmlSchemaSimpleType.html。但让我们看看如何处理复杂类型。让我们从一个简单的方法开始:
@Override\npublic List<QName> getChildElementNames(QName parentElementName) {\n XmlSchemaElement element = xmlSchemaCollection.getElementByQName(parentElementName);\n XmlSchemaType type = element != null ? element.getSchemaType() : null;\n\n List<QName> result = new LinkedList<>();\n if (type instanceof XmlSchemaComplexType) {\n addElementNames(result, (XmlSchemaComplexType) type);\n }\n return result;\n}\nRun Code Online (Sandbox Code Playgroud)\n\nXmlSchemaComplexType可以代表真实类型和元素extension。请参阅类public static QName getBaseType(XmlSchemaComplexType type)的方法XmlSchemaUtils。
private void addElementNames(List<QName> result, XmlSchemaComplexType type) {\n XmlSchemaComplexType baseType = getBaseType(type);\n XmlSchemaParticle particle = baseType != null ? baseType.getParticle() : type.getParticle();\n\n addElementNames(result, particle);\n}\nRun Code Online (Sandbox Code Playgroud)\n\n当您处理 时XmlSchemaParticle,请考虑它可以有多种实现。请参阅: https: //ws.apache.org/commons/XmlSchema/apidocs/org/apache/ws/commons/schema/XmlSchemaParticle.html
private void addElementNames(List<QName> result, XmlSchemaParticle particle) {\n if (particle instanceof XmlSchemaAny) {\n\n } else if (particle instanceof XmlSchemaElement) {\n\n } else if (particle instanceof XmlSchemaGroupBase) {\n\n } else if (particle instanceof XmlSchemaGroupRef) {\n\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n另一件要记住的事情是元素可以是抽象的,也可以是具体的。同样,JavaDocs 是最好的指导。
\n| 归档时间: |
|
| 查看次数: |
10829 次 |
| 最近记录: |