Perché XmlDocument.GetElementById tornare sempre nullo?
-
04-10-2019 - |
Domanda
ho delle XML (validato XHTML) che assomiglia a questo:
<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>
E sto cercando di ottenere il nodo di #myHeader
utilizzando docment.GetElementById("myHeader")
ma restituisce sempre null
. Perché?
Sono indovinare che non riconosce l'attributo id
come il attributo id senza un DTD o qualcosa del genere? Se questo è il caso, come posso farlo utilizzare un HTML DTD?
Soluzione
E 'perché XmlDocument sa nulla di ciò che un mezzo id
. È necessario includere un DTD nel documento XHTML. Basta mettere il seguente all'inizio del file HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Esempio:
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");
Si noti che questo potrebbe essere un po 'più lento, perché il DTD deve essere scaricato.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow