【问题标题】:XMLDocument GetElementByID returning nullXMLDocument GetElementByID 返回 null
【发布时间】:2023-03-26 12:52:01
【问题描述】:

我正在尝试使用函数 GetElementById 获取 xml 的元素,但该函数总是返回 null。

//get xml text from a web service
string xml = aS.createTree();
XmlDocument tree = new XmlDocument();
tree.LoadXml(xml);

//get all nodes with the tag name "item"
XmlNodeList node = tree.GetElementsByTagName("item");
//just for test to see if i could get the attribute value which returns the expected
string idTemp = node[0].Attributes["ID"].Value;
XmlElement elem = tree.GetElementById("1");

elem 总是返回 null。你们能帮帮我吗?

顺便说一下,这是我要解析的 xml:

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE tree [
   <!ELEMENT tree ANY>
   <!ELEMENT item ANY>
   <!ATTLIST item id ID #REQUIRED>
]>
<tree>
   <item id="1">
       <item id="2"></item>
   </item>
   <item id="5">
       <item id="6"></item>
       <item id="7">
           <item id="8">
               <item id="10">
                   <item id="11"></item>
               </item>
           </item>
           <item id="9"></item>
       </item>
   </item>
</tree>

【问题讨论】:

    标签: c# xml null getelementbyid xmldocument


    【解决方案1】:

    只需将ID 更改为id

    string idTemp = node[0].Attributes["id"].Value;
    

    但请注意:

    XmlDocument.GetElementById来自 MSDN:

    DOM 实现必须具有定义哪些属性属于 ID 类型的信息。尽管可以在 XSD 模式或 DTD 中定义类型 ID 的属性,但此版本的产品仅支持在 DTD 中定义的属性。除非在 DTD 中如此定义,否则名为“ID”的属性不属于 ID 类型。未知属性是否为 ID 类型的实现应返回 null。

    【讨论】:

      【解决方案2】:

      据我所知,id att 不能以数字开头。你可以试试id="_1" 之类的东西,看看它是如何工作的。

      【讨论】:

        【解决方案3】:

        https://www.w3schools.com/tags/att_global_id.asp

        HTML 4.01 和 HTML5 的区别

        注意:HTML 4.01 对 id 值的内容有更大的限制(例如;在 HTML 4.01 中,id 值不能以数字开头)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-07-13
          • 1970-01-01
          • 1970-01-01
          • 2014-08-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多