奇怪的行为 XmlDocument.LoadXML 和 GetElementByID,如何用引号删除字符串
这是一些 C# 代码
string webPageStr = @"<html><body><div id=""content"">good content</div><div id=""badcontent"">bad content</div></body></html>";
XmlDocument webPage = new XmlDocument();
webPage.LoadXml(webPageStr);
XmlElement divElement = webPage.GetElementById("content");
,divElement 等于 null,我不知道为什么
我也尝试像这样声明 webPageStr,
string webPage = @"<html><body><div id="content">good content</div><div id="badcontent">bad content</div></body></html>";
但 XmlDocument 抛出异常 System.Xml.XmlException: "&" bad token
这段代码有什么问题吗?
Here's some c# code
string webPageStr = @"<html><body><div id=""content"">good content</div><div id=""badcontent"">bad content</div></body></html>";
XmlDocument webPage = new XmlDocument();
webPage.LoadXml(webPageStr);
XmlElement divElement = webPage.GetElementById("content");
and divElement is equal null and i don't know why
I have also tried declare webPageStr like that
string webPage = @"<html><body><div id="content">good content</div><div id="badcontent">bad content</div></body></html>";
but XmlDocument throws en exception System.Xml.XmlException: "&" bad token
Whats wrong with this code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果要使用 GetElementById 方法。 这是因为该函数不知道 ID 对于给定的 XML 意味着什么。 在您的情况下,您使用的是 XHTML,因此您需要指定当您想通过 id 查找元素时,这意味着查找具有名为“id”属性的节点:
第一种方法意味着您需要通过 Web 访问 DOCTYPE 声明运行代码时(http://www.w3.org/TR /xhtml1/DTD/xhtml1-transitional.dtd)
另一种方法是使用 XPATH 表达式:
You need to include a DOCTYPE declaration if you want to use the GetElementById method. It is because the function doesn't know what ID means for the given XML. In your case you are using XHTML, so you need to specify that when you want to find an element by id this means find a node that has an attribute named "id":
This first approach means that you need web access to the DOCTYPE declaration when running your code (http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd)
An alternative approach would be to use XPATH expression: