简体   繁体   English

在python中使用minidom设置DTD

[英]Set a DTD using minidom in python

I am trying to include a reference to a DTD in my XML doc using minidom. 我正在尝试使用minidom在我的XML文档中包含对DTD的引用。

I am creating the document like: 我正在创建文档,如:

doc = Document()
foo = doc.createElement('foo')
doc.appendChild(foo)
doc.toxml()

This gives me: 这给了我:

<?xml version="1.0" ?>
<foo/>

I need to get something like: 我需要得到类似的东西:

<?xml version="1.0" ?>
<!DOCTYPE something SYSTEM "http://www.path.to.my.dtd.com/my.dtd">
<foo/>

The documentation is out of date. 文档已过期。 Use the source, Luke. 使用来源,卢克。 I do it something like this. 我做这样的事情。

from xml.dom.minidom import DOMImplementation

imp = DOMImplementation()
doctype = imp.createDocumentType(
    qualifiedName='foo',
    publicId='', 
    systemId='http://www.path.to.my.dtd.com/my.dtd',
)
doc = imp.createDocument(None, 'foo', doctype)
doc.toxml()

This prints the following. 这将打印以下内容。

<?xml version="1.0" ?><!DOCTYPE foo  SYSTEM \'http://www.path.to.my.dtd.com/my.dtd\'><foo/>

Note how the root element is created automatically by createDocument(). 请注意createDocument()如何自动创建根元素。 Also, your 'something' has been changed to 'foo': the DTD needs to contain the root element name itself. 此外,您的“某些内容”已更改为“foo”:DTD需要包含根元素名称本身。

根据Python文档 ,minidom中没有DocumentType接口的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM