使用Java查找可在xml架构中重复的项目

时间:2013-07-04 13:04:19

标签: java xml xsd

我想从XML模式中推断出(parentTag, childTag)对,以便parentTag允许childTag多个maxOccurs实例作为直接子项。

手动执行此操作,我在模式中查找<xs:complexType name="aType"> <xs:sequence> <xs:element ref="B" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> <xs:element name="A" type="aType"> <xs:element name="ANOTHER" type="aType"> 属性,查看元素标记和直接父级的标记。

例如,来自

(A,B)

我应该获得情侣(ANOTHER,B)(parentTag, childTag)

我有一个使用XSLT的工作解决方案将我的架构转换为此类{{1}}对夫妇的列表。

在Java中有优雅的方法吗?您建议使用哪个库来实现它?

1 个答案:

答案 0 :(得分:1)

要在Java中处理XML模式(不使用XSLT),我们使用Xerces2 Java Parser:http://xerces.apache.org/xerces2-j/

可能需要以下包/类:

import org.w3c.dom.*;
import org.apache.xerces.xs.*;
import org.apache.xerces.dom.DOMXSImplementationSourceImpl;
import org.apache.xerces.impl.xs.util.StringListImpl;
import org.apache.xerces.util.XMLCatalogResolver;

然后,XSD文件的处理如下:

// Obtain the XML Schema implementation
XSImplementation impl = (XSImplementation)
  (new DOMXSImplementationSourceImpl()).getDOMImplementation(XMLConstants.XSD_LOADER_NAME);

// Get schema loader
XSLoader schemaLoader = impl.createXSLoader (null);

// Optional. Specify error handler
DOMErrorHandler errorHandler = ....;
DOMConfiguration config = schemaLoader.getConfig();
config.setParameter("error-handler", errorHandler);

// Optional. Specify XML catalog resolver.
// This may be needed to redirect internal DTD/schema file references
XMLCatalogResolver catalogResolver = ...;
config.setParameter("resource-resolver", catalogResolver);

String xsdURI = ...; // the location of schema file

// read schema
XSModel xsModel = schemaLoader.loadURI(xsdURI);

// PROCESS SCHEMA (here, you can do anything you want)

XSNamedMap xsMap;

// process top-level element declarations
xsMap = xsModel.getComponents(XSConstants.ELEMENT_DECLARATION);
for (int i = 0; i < xsMap.getLength(); i ++)
{
  XSElementDeclaration xsElementDecl = (XSElementDeclaration) xsMap.item(i);
  ...
}

// process top-level type definitions
xsMap = xsModel.getComponents(XSConstants.TYPE_DEFINITION);
for (int i = 0; i < xsMap.getLength(); i ++)
{
  XSTypeDefinition xsTDef = (XSTypeDefinition) xsMap.item(i);
  ...
}

// process model group definitions
xsMap = xsModel.getComponents(XSConstants.MODEL_GROUP_DEFINITION);
for (int i = 0; i < xsMap.getLength(); i ++)
{
  XSModelGroupDefinition xsGroupDef = (XSModelGroupDefinition) xsMap.item(i);
  ...
}

...