cvc-elt.1: не удается найти объявление элемента 'NewIssue'

1

Я пытаюсь проверить XML-документ в памяти, прежде чем записывать его в файл. Я нашел много подобных вопросов для своей проблемы, но здесь есть разница, я бы так подумал. Для этой проверки определены несколько схем, а параметр "переопределить" используется в их отношениях от родителя к детям следующим образом: CoreSchema.xsd → CenterSchema.xsd → CenterSchema_REF.xsd

CoreSchema.xsd (только образец, не полный, из-за политики безопасности)

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="http://www.example.com/supplier" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.com/supplier" elementFormDefault="qualified" attributeFormDefault="unqualified" version="1.8">
<xs:element name="NewIssue">
    <xs:annotation>
        <xs:documentation>Root element to add new issues</xs:documentation>
    </xs:annotation>
    <xs:complexType>
        <xs:sequence>
            <xs:element name="NewIssueList">
                <xs:annotation>
                    <xs:documentation>Contains a list of issues</xs:documentation>
                </xs:annotation>
                <xs:complexType>
                    <xs:sequence maxOccurs="unbounded">
                        <xs:element name="Issue" type="ImportIssueType"/>
                    </xs:sequence>
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>
...
...

CenterSchema.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="http://www.example.com/supplier" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://http://www.example.com/supplier" elementFormDefault="qualified" attributeFormDefault="unqualified" version="1.8">
<xs:redefine schemaLocation="CoreSchema.xsd">
    <xs:complexType name="Issue">
        <xs:complexContent>
            <xs:extension base="Issue">
                <xs:sequence>
                    <xs:element name="Component" type="Components"/>
                    <xs:element name="Keywords" type="Keywords" minOccurs="0"/>
                    <xs:element name="SupplierStatus" type="SupplierStatus" minOccurs="0"/>
                </xs:sequence>
            </xs:extension>
        </xs:complexContent>
    </xs:complexType>
    <xs:complexType name="ImportIssueType">
        <xs:annotation>
            <xs:documentation>Definition of a exported issue</xs:documentation>
        </xs:annotation>
        <xs:complexContent>
            <xs:extension base="ImportIssueType">
                <xs:sequence>
                    <xs:element name="Component" type="Components">
                        <xs:annotation>
                            <xs:documentation>Describes the component where the issue occurs.</xs:documentation>
                        </xs:annotation>
                    </xs:element>
                    <xs:element name="Keywords" type="Keywords" minOccurs="0">
                        <xs:annotation>
                            <xs:documentation>Keyword applied for the issue.</xs:documentation>
                        </xs:annotation>
                    </xs:element>
                </xs:sequence>
            </xs:extension>
        </xs:complexContent>
    </xs:complexType>
...
...
</xs:redefine>
</xs:schema>

CenterSchema_REF.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns="http://www.example.com/supplier" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.com/supplier" elementFormDefault="qualified" attributeFormDefault="unqualified" version="4.7">
<xs:redefine schemaLocation="CenterSchema.xsd">
...
...
</xs:redefine>

EDITED: Сериализованный документ (написанный в.xml файле) выглядит следующим образом:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<NewIssue xmlns="http://www.example.com/supplier" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.com/supplier CenterSchema_REF.xsd">
<NewIssueList>    
<Issue>
  <SupplierID>574</SupplierID>
  <NewIssueMode>Read Only</NewIssueMode>
  <Author>
    <Name/>
  </Author>
  <Category>Software</Category>
  <ItemType>Test-Issue</ItemType>
  <IssueClass>Issue</IssueClass>
  <DetectedOnDate>2014-08-14</DetectedOnDate>
  <Device>TEST</Device> 
  <Severity>1</Severity>
  <Supplier>
    <ContactName/>
    <Data>Analysis: [Reason of problem] [Condition for defect] [Impact] [Risk] [Root cause]</Data>
    <Status>Supplier Not Assigned</Status>
    <StatusInternal>SUBMITTED</StatusInternal>
  </Supplier>
...
... 
</Issue>
</NewIssueList>
</NewIssue>

Я внедрил SchemaFactory и проверку следующим образом:

private boolean toFile(final String outputPath, final Node document) {
    boolean resultOk = false;
    try {
        DOMSource domSource = new DOMSource(document);          
        SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        factory.setResourceResolver(new CustomResourceResolver());

            try {   
                InputStream schemaCSREF = DxiParser.class.getResourceAsStream("/CenterSchema_REF.xsd");
                factory.setFeature("http://apache.org/xml/features/honour-all-schemaLocations", true);
                factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", false);                    
                Source source = new StreamSource(schemaCSREF);
                Schema schema = factory.newSchema(source);
                Validator validator = schema.newValidator();
                validator.validate(domSource);
            } catch (SAXException e) {
                // instance document is invalid!
                System.out.println(e.getLocalizedMessage());            
                System.out.println("\n** SAX Parser: Error during validation of " +document.getNodeName());
                return false;
            }

            FileOutputStream xmlOut = new FileOutputStream(new File(outputPath));
            StreamResult streamResult = new StreamResult(xmlOut);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer serializer = tf.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            // serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"users.dtd");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.transform(domSource, streamResult);
            xmlOut.close();
            resultOk = true;

        // ---- Error handling ----
    } catch (TransformerConfigurationException tce) {
        System.out.println("\n** Transformer Factory error");
        System.out.println("   " + tce.getMessage());
        Throwable e = (tce.getException() != null) ? tce.getException()
                : tce;
        e.printStackTrace();
    } catch (TransformerException tfe) {
        System.out.println("\n** Transformation error");
        System.out.println("   " + tfe.getMessage());
        Throwable e = (tfe.getException() != null) ? tfe.getException()
                : tfe;
        e.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    return resultOk;
}

CustomResourceResolver реализован следующим образом:

public class CustomResourceResolver implements LSResourceResolver {

@Override
public LSInput resolveResource(String type, String namespaceURI,
        String publicId, String systemId, String baseURI) {

    LSInputImpl input = new LSInputImpl();      
    InputStream stream = null;
    try {           
        stream = new FileInputStream(new File(systemId));
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    input.setPublicId(publicId);
    input.setSystemId(systemId);
    input.setBaseURI(baseURI);
    input.setCharacterStream(new InputStreamReader(stream));

    return input;

}

}

и реализация LSInput является стандартной:

public class LSInputImpl implements LSInput{

private Reader characterStream;
private InputStream byteStream;
private String stringData;
private String systemId;
private String publicId;
private String baseURI;
private String encoding;
private boolean certifiedText;

//getters and setters
}

Я могу подтвердить, что все файлы схемы загружаются (находятся в путях) и заполняются объектом Schema. Я вижу в поле Grammar объекта Schema, что все сложные типы обнаружены, и я вижу эту конкретную запись, загруженную в массив XSComplexTypeDecl:

Тип сложного типа = ' http://www.example.com/supplier,#AnonType_NewIssue ', имя базового типа = 'anyType', тип контента = 'ELEMENT', isAbstract = 'false', hasTypeId = 'false', final = '0', block = '0', particle = '(" http://www.example.com/supplier ": NewIssueList)', производныйBy = 'ОГРАНИЧЕНИЕ'.

так что это доказательство того, что CoreSchema достигнут через CenterSchema, который достигается через CenterSchema_REF. ПРИМЕЧАНИЕ. Когда я устанавливаю заводскую функцию " http://apache.org/xml/features/validation/schema-full-checking " в true, поле XSComplexTypeDecl равно null.

Пытался добавить все 3 xsds в качестве источника [], ошибка такая же. Пробовал экспериментировать с настройкой разных заводских функций на true/false.

Я не знаю, что еще проверить, полностью застрял.

Если есть необходимость, я могу добавить дополнительную информацию. Спасибо всем.

  • 0
    Непонятно, в чем конкретно твой вопрос. Документ в памяти (как вы воспроизводите его) не имеет правильной формы (этот конечный тег для «протоколов», похоже, не соответствует ни одному начальному тегу).
  • 0
    После редактирования: Спасибо, мистер Сперберг, за то, что указал на это. Это была на самом деле ошибка копирования-вставки. XML правильно сформирован (я проверяю его в других коммерческих валидаторах XML по этому набору из 3 схем, и это нормально.) Вопрос в заголовке вопроса - почему я не могу обнаружить объявление элемента, если оно загружено через CustomResourceResolver?
Теги:
xsd
saxparser

1 ответ

0

В качестве обходного пути я решил проблему, фактически проверив экземпляр после сериализации, загрузив его из файловой системы.

            try {   
            InputStream schemaCSAPC = new FileInputStream(schemaFile);
            factory.setFeature("http://apache.org/xml/features/honour-all-schemaLocations", true);
            factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", false);                    

            FileOutputStream xmlOut = new FileOutputStream(new File(outputPath));
            StreamResult streamResult = new StreamResult(xmlOut);
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer serializer = tf.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
            // serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"users.dtd");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.transform(domSource, streamResult);

            xmlOut.close();
            Source source = new StreamSource(new FileInputStream(outputPath));
            Source shemaSource = new StreamSource(schemaCSREF);
            Schema schema = factory.newSchema(shemaSource);
            Validator validator = schema.newValidator();
            validator.validate(source);
            } catch (SAXException e) {
                // instance document is invalid!            
                System.out.println("\n** SAX Parser: Error during validation of " +document.getNodeName());
                return false;
            }

Тем не менее, это не соответствует требованию, но, по крайней мере, я не заблокирован и не могу управлять.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню