本文介绍了为什么 XmlDocument.GetElementById 总是返回 null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些像这样的 XML(有效的 XHTML):

I've got some XML (valid XHTML) that looks like this:

<html>
    <head>
        <script type="text/javascript">
            <![CDATA[
                function change_header(){
                    document.getElementById("myHeader").innerHTML="Nice day!";
                }]]>
        </script>
    </head>
    <body>
        <h1 id="myHeader">Hello World!</h1>
        <button onclick="change_header()">Change text</button>
    </body>
</html>

我正在尝试使用 docment.GetElementById("myHeader") 获取 #myHeader 节点,但它总是返回 null.为什么?

And I'm trying to get the #myHeader node using docment.GetElementById("myHeader") but it always returns null. Why?

猜测它不会将 id 属性识别为 id 属性而没有 DTD 之类的?如果是这种情况,我怎样才能让它使用 HTML DTD?

I'm guessing it doesn't recognize the id attribute as the id attribute without a DTD or something? If that's the case, how can I get it to use an HTML DTD?

推荐答案

这是因为 XmlDocument 对 id 的含义一无所知.您需要在 XHTML 文档中包含 DTD.只需将以下内容放在 html 文件的开头:

It's because XmlDocument knows nothing about what an id means. You need to include a DTD in your XHTML document. Just put the following in the beginning of your html file:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

示例:

string html = @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd""><html><body><div id=""foo"">some content</div></body></html>";
XmlDocument document = new XmlDocument();
document.LoadXml(html);
XmlElement div = document.GetElementById("foo");

请注意,这可能会慢一点,因为需要下载 DTD.

Notice that this might be a little slower because the DTD needs to be downloaded.

这篇关于为什么 XmlDocument.GetElementById 总是返回 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 22:19