使用正则表达式通过 XSD 验证 XML 值



我目前有以下格式的XML:

<?xml version="1.0"?>
<trace_data>
  <pinfo>1</pinfo>
  <traces>
    <P0>21:39:09.776762 clock_gettime(CLOCK_BOOTTIME, {68, 27131557}) = 0
</P0>
    <P1>21:39:09.776831 epoll_ctl(4, EPOLL_CTL_DEL, 60, NULL) = 0
</P1>
    <P2>21:39:09.776856 close(60)               = 0
</P2>
  </traces>
</trace_data>

其中,流程元素(P0、P1 等(应形成最多 n 个进程 (P0 ...Pn(

我现在正在尝试创建一个 XSD 来验证这些 XML。另一个重要的特征应该是每个进程的值应该以一个时间开头(例如 21:39:09.123123(。

我想出了以下 XSD,但无法弄清楚如何验证流程元素的值。

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="https://www.w3schools.com"
xmlns="https://www.w3schools.com"
elementFormDefault="qualified">

<xs:element name="trace_data">
  <xs:complexType>
    <xs:element name = "pinfo" type="xs:string"/>
    <xs:element name = "traces" type="Process"/>
  </xs:complexType>
</xs:element>

<!-- <THIS DESCRIBES P0 to Pn FOR WINDOWSIZE n> -->
<xs:complexType name="Process">
        <xs:sequence>
            <xs:any minOccurs="1" maxOccurs="unbounded" processContents="lax"/>
        </xs:sequence>
    <xs:assert test=" "
</xs:complexType> 
<!-- <PROCESS ENDS HERE> -->

</xs:schema> 

谁能帮助我或为我指出正确的方向?

提前谢谢。

设计这种XML格式的人并没有考虑在XSD中什么工作得很好,或者就此而言,与任何其他XML工具一起工作。像这样使用结构化元素名称感觉像是一个聪明的主意,但实际上是一个彻头彻尾的麻烦。

一种方法是将验证作为两步过程进行:首先将 XML 转换为更传统(且更易于处理(的内容:

<traces>
    <P nr="0" time="21:39:09.776762">clock_gettime(CLOCK_BOOTTIME, {68, 27131557}) = 0</P>
    <P nr="1" time="21:39:09.776831">epoll_ctl(4, EPOLL_CTL_DEL, 60, NULL) = 0</P>
...
</traces>

然后将 XSD 应用于结果,这现在更加简单。

尽管您仍然需要 XSD 1.1 断言来验证数字是否形成正确的序列:

<xsd:assert test="not(P[position() != @nr + 1])"/>

最新更新