gpt4 book ai didi

java - 获取 XSD 验证错误的父元素

转载 作者:数据小太阳 更新时间:2023-10-29 02:23:30 25 4
gpt4 key购买 nike

我有以下带有单位和度量子元素的 xml。

<Depth>
<measure>1.00</measure>
<unit>in</unit>
<Depth>
<Width>
<measure>1.00</measure>
<unit>in</unit>
</Width>
<vendorPackHeight>
<measure>1.00</measure>
<unit>in</unit>
</vendorPackHeight>
<Weight>
<measure>7.00</measure>
<unit>LBS</unit> //invalid expected value is lb
</Weight>

当单位或度量子元素的 XSD 验证失败并出现类似 cvc-enumeration-valid 的错误(当度量不是来自一组枚举值时)或单位值因 cvc-datatype-valid.1.2.1 而失败时数据类型不匹配如何获取父元素?在上面的 xml 中,它将是重量。

在 SAXParseException 中,我得到了发生错误的行号。是否可以从行号中获取元素,然后获取其父元素?

最佳答案

我认为在 Java API 中没有执行此操作的标准方法。但是,某些库确实允许您偷看它当前在哪个元素上。例如在 Apache Xerces 实现中,它支持通过

获取当前节点

getProperty("http://apache.org/xml/properties/dom/current-element-node")

在他们的网站上查看有关该属性的文档:https://xerces.apache.org/xerces2-j/properties.html#dom.current-element-node


Xerces library默认情况下由您的 JDK 提供,但也可以作为第 3 方库导入到您的项目中。如果您必须拥有它才能正确运行您的应用程序,我建议您添加它。下面是一些示例代码,用于验证 XSD 的 XML 文档并获取当前节点。

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.apache.xerces.impl.Constants;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;

public class XSDTest {

public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException {

// our XSD, which defines 1 node <TheNode> which must have decimal text content
byte [] schemaData = ("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
+ "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">"
+ "<xs:simpleType name=\"theNodeType\">"
+ "<xs:restriction base=\"xs:decimal\"/>"
+ "</xs:simpleType>"
+ "<xs:element name=\"TheNode\" type=\"theNodeType\"/>"
+ "</xs:schema>").getBytes();
// our invalid xml
byte [] xmlData = "<TheNode>123NotADecimal</TheNode>".getBytes();

// parse schema
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Source schemaSource = new StreamSource(new ByteArrayInputStream(schemaData));
Schema schema = schemaFactory.newSchema(schemaSource);

// build our document, must use document builder to enable xerces parser properties for DOM
// Also must be a xerces implementation of the DBF, should be enabled by default in a standard java project but just to be verbose about it
// pass in the full name of the DBF impl
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(org.apache.xerces.jaxp.DocumentBuilderFactoryImpl.class.getName(), XSDTest.class.getClassLoader());
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(xmlData));


// configure our validator and parse the document.
Validator validator = schema.newValidator();
validator.setErrorHandler(new MyErrorHandler(validator));
validator.validate(new DOMSource(doc.getDocumentElement()));
}

private static class MyErrorHandler implements ErrorHandler {
private final Validator xsdValidator;

public MyErrorHandler(Validator xsdValidator) {
this.xsdValidator = xsdValidator;
}
@Override
public void warning(SAXParseException exception) throws SAXException {
System.out.println("Warning on node: " + getCurrentNode());
System.out.println(exception.getLocalizedMessage());
}

@Override
public void error(SAXParseException exception) throws SAXException {
System.out.println("Error on node: " + getCurrentNode());
System.out.println(exception.getLocalizedMessage());
}

@Override
public void fatalError(SAXParseException exception) throws SAXException {
System.out.println("Fatal on node: " + getCurrentNode());
System.out.println(exception.getLocalizedMessage());
}


private Node getCurrentNode() throws SAXNotRecognizedException, SAXNotSupportedException {
// get prop "http://apache.org/xml/properties/dom/current-element-node"
// see https://xerces.apache.org/xerces2-j/properties.html#dom.current-element-node
return (Node)xsdValidator.getProperty(Constants.XERCES_PROPERTY_PREFIX + Constants.CURRENT_ELEMENT_NODE_PROPERTY);
}
}

}

输出:

Error on node: [TheNode: null]
cvc-datatype-valid.1.2.1: '123NotADecimal' is not a valid value for 'decimal'.
Error on node: [TheNode: null]
cvc-type.3.1.3: The value '123NotADecimal' of element 'TheNode' is not valid.

关于java - 获取 XSD 验证错误的父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38577102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com