【问题标题】:Using a DTD, can an element be declared that allows any XML content?使用 DTD,是否可以声明允许任何 XML 内容的元素?
【发布时间】:2013-06-18 00:36:29
【问题描述】:

我正在尝试为 XML 文档创建 DTD。该文档有两个孩子 - 一个包含结构化数据,另一个包含非结构化数据,例如;

<doc>
  <structured>
    <foo x="9"/>
    <foo x="4"/>
  </structured>
  <unstructured>
    <hello/>
    <world x="2">
      <hi msg="something"/>
      <anything/>
    </world>
  </unstructured>
</doc>

我想为上述 XML 创建一个 DTD,它允许 &lt;unstructured&gt; 元素包含任何有效的 XML。我试过这个DTD;

<!ELEMENT doc (structured,unstructured)
<!ELEMENT structured (foo*)
<!ELEMENT foo EMPTY>
<!ATTLIST foo x CDATA #REQUIRED>
<!ELEMENT unstructured ANY>

但是错误是这样产生的;

No declaration for element hello
No declaration for element world

..等

我想允许&lt;unstructured&gt; 包含任何有效的 XML。 DTD 中有没有办法允许指定的元素包含任何可解析的 XML?

我正在使用 PHP 5.3 DOMDocument::validate。

【问题讨论】:

    标签: xml validation dtd


    【解决方案1】:

    不,没有。

    通过使用ANY 关键字,您已尽可能接近 DTD。但是ANY 匹配#PCDATA 和DTD 中声明的每个元素的混合。它不接受未声明的元素; DTD 没有太多关于部分有效性的概念。

    这是在 XSD 中引入通配符的激励用例之一,可以选择要求对匹配元素进行严格、宽松或跳过处理。

    【讨论】:

      【解决方案2】:

      格式正确是无效的,这是简单的答案。如果您想使用 DTD 验证文档,则必须声明每个元素(与 xml 模式不同)。工作示例如下所示:

      <?xml version="1.0"?>
      <!DOCTYPE doc [
      <!ELEMENT doc (structured,unstructured)>
      <!ELEMENT structured (foo*)>
      <!ELEMENT hello EMPTY>
      <!ELEMENT world (hi, anything)>
      <!ATTLIST world x CDATA #REQUIRED>
      <!ELEMENT hi EMPTY>
      <!ATTLIST hi msg CDATA #REQUIRED>
      <!ELEMENT anything EMPTY>
      <!ELEMENT foo EMPTY>
      <!ATTLIST foo x CDATA #REQUIRED>
      <!ELEMENT unstructured ANY>
      ]>
      <doc>
        <structured>
          <foo x="9"/>
          <foo x="4"/>
        </structured>
        <unstructured>
          <hello/>
          <world x="2">
            <hi msg="something"/>
            <anything/>
          </world>
        </unstructured>
      </doc>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-01
        • 1970-01-01
        相关资源
        最近更新 更多