在xml元素中重复检查

时间:2017-01-02 13:02:22

标签: xml xslt xsd

我需要在xml元素属性值中进行重复检查。

示例输入请求:

 <Parent>
   <child id="1"> test 1</child>
   <child id="1"> test 2</child>
   <child id="2"> test 3</child>
</parent>

我想找到使用XSD的请求xml中的子元素属性中存在的重复id或其他方式会很好。任何人都可以帮我检测重复的元素属性值。

1 个答案:

答案 0 :(得分:1)

基本上,您需要使用xsd:unique来强制元素或属性的唯一性。以下是该链接的摘录:

  

指定属性或元素值(或组合   属性或元素值)在指定的内容中必须是唯一的   范围。该值必须是唯一的或无。

如果您不知道,那么您需要创建一个XSD / DTD,使用该XSD / DTD可以强制执行此唯一性,然后使用任何可用的XML解析器针对该XSD / DTD验证XML。下面是一个Java示例以及XSD。

您的陈述:

  

使用XSD或其他方式请求xml可以正常

据我所知,如果您想检查XML文档的有效性,那么您必须拥有XSDDTD,没有其他方法可以做到XSD或DTD(或鲜为人知的RELAX NG)。因此,您需要做的就是编写一个XSD或DTD来定义XML文档的预期结构,然后使用一些XML验证器来验证您的XML文档与XSD / DTD的对比,它将告诉您XML文档是否符合XSD / DTD与否。 底线是您需要编写/指定XSD / DTD,它定义了XML文档的预期结构

您的XML:&#34; so.xml&#34;

<Parent>
   <child id="1"> test 1</child>
   <child id="2"> test 2</child>
   <child id="2"> test 3</child>
</Parent>

您需要的示例XSD(xsd:您的要求是唯一的):&#34; so.xsd&#34;

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:element name="Parent">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="child" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:simpleContent>
                            <xs:extension base="xs:string">
                                <xs:attribute name="id" type="xs:token" use="required"/>
                            </xs:extension>
                        </xs:simpleContent>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    <!-- This is the solution of your problem - "xs:unique" -->   
    <xs:unique name="unique-id">
          <xs:selector xpath="child"/>
          <xs:field xpath="@id"/>
       </xs:unique>
    </xs:element>
</xs:schema>

用于验证的示例Java代码:

import org.w3c.dom.Document; 
import org.xml.sax.SAXException; 
import org.xml.sax.SAXParseException; 
import org.xml.sax.InputSource; 


import java.io.File; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.StringReader; 


import javax.xml.XMLConstants; 
import javax.xml.parsers.DocumentBuilder; 
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; 

public class XmlSchemaValidationHelper { 

    public static void main(String[] argv) {
        XmlSchemaValidationHelper schemaValidationHelper = new XmlSchemaValidationHelper();
        schemaValidationHelper.validateAgainstSchema(new File(argv[0]), new File(argv[1]));
    }

    public void validateAgainstSchema(File xmlFile, File xsdFile) { 
        try {
            System.out.println("### Starting...");
            // parse an XML document into a DOM tree 
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 
            builderFactory.setNamespaceAware(true); 
            DocumentBuilder parser = builderFactory.newDocumentBuilder(); 
            Document document = parser.parse(xmlFile); 

            // create a SchemaFactory capable of understanding WXS schemas 
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 

            // load a WXS schema, represented by a Schema instance 
            Source schemaFile = new StreamSource(xsdFile); 
            Schema schema = factory.newSchema(schemaFile); 

            // create a Validator instance, which can be used to validate an 
            // instance document 
            Validator validator = schema.newValidator(); 

            // validate the DOM tree 
            validator.validate(new DOMSource(document));
            System.out.println("### Finished...");

        } catch (FileNotFoundException ex) { 
            throw new OpenClinicaSystemException("File was not found", ex.getCause()); 
        } catch (IOException ioe) { 
            throw new OpenClinicaSystemException("IO Exception", ioe.getCause()); 
        } catch (SAXParseException spe) { 
            spe.printStackTrace(); 
            throw new OpenClinicaSystemException("Line : " + spe.getLineNumber() + " - " + spe.getMessage(), spe.getCause()); 
        } catch (SAXException e) { 
            throw new OpenClinicaSystemException(e.getMessage(), e.getCause()); 
        } catch (ParserConfigurationException pce) { 
            throw new OpenClinicaSystemException(pce.getMessage(), pce.getCause()); 
        } 
    } 

    public class OpenClinicaSystemException extends RuntimeException { 
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        private String errorCode; 
        private Object[] errorParams; 

        public OpenClinicaSystemException(String code, String message) { 
            this(message); 
            this.errorCode = code; 
        } 

        public OpenClinicaSystemException(String code, String message, Throwable cause) { 
            this(message, cause); 
            this.errorCode = code; 
        } 

        public OpenClinicaSystemException(String message, Throwable cause) { 
            super(message, cause); 
        } 

        public OpenClinicaSystemException(Throwable cause) { 
            super(cause); 
        } 

        public OpenClinicaSystemException(String message) { 
            super(message); 
            this.errorCode = message; 
        } 

        public OpenClinicaSystemException(String code, Object[] errorParams) { 
            this.errorCode = code; 
            this.errorParams = errorParams; 
        } 

        public OpenClinicaSystemException(String code, Object[] errorParams, String message) { 
            this(message); 
            this.errorCode = code; 
            this.errorParams = errorParams; 
        } 

        public String getErrorCode() { 
            return errorCode; 
        } 

        public Object[] getErrorParams() { 
            return errorParams; 
        } 

        public void setErrorParams(Object[] errorParams) { 
            this.errorParams = errorParams; 
        } 
    }

}

您可以将此程序作为 - java XmlSchemaValidationHelper so.xml so.xsd

运行