在 python 中使用 minidom 设置 DTD

发布于 2024-08-23 08:19:57 字数 416 浏览 4 评论 0原文

我正在尝试使用 minidom 在我的 XML 文档中包含对 DTD 的引用。

我正在创建这样的文档:

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

这给了我:

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

我需要得到类似的东西:

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

I am trying to include a reference to a DTD in my XML doc using minidom.

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/>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情魔剑神 2024-08-30 08:19:57

该文档已过时。使用来源,卢克。我这样做是这样的。

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()

这将打印以下内容。

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

请注意 createDocument() 如何自动创建根元素。另外,您的“something”已更改为“foo”:DTD 需要包含根元素名称本身。

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(). Also, your 'something' has been changed to 'foo': the DTD needs to contain the root element name itself.

两仪 2024-08-30 08:19:57

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

According to the Python docs, there is no implementation of the DocumentType interface in the minidom.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文