¿Por qué siempre vuelven XmlDocument.GetElementById nula?
-
04-10-2019 - |
Pregunta
Tengo un poco de XML (XHTML) que es similar al siguiente:
<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>
Y estoy tratando de conseguir el nodo #myHeader
usando docment.GetElementById("myHeader")
pero siempre devuelve null
. ¿Por qué?
Me adivinanzas que no reconoce el atributo id
como la atributo id sin un DTD o algo? Si ese es el caso, ¿cómo puedo conseguir que se utilice una DTD HTML?
Solución
Es porque XmlDocument no sabe nada de lo que significa una id
. Es necesario incluir una DTD en el documento XHTML. Sólo hay que poner lo siguiente en el comienzo de su archivo html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Ejemplo:
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");
Tenga en cuenta que esto podría ser un poco más lento debido a que el DTD necesita ser descargado.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow