使用 HTML Agility Pack 替换 HTML div InnerText 标记
我正在使用 HTML Agility Pack 来操作和编辑 HTML 文档。我想更改字段中的文本,如下所示:
<div id="Div1"><b>Some text here.</b><br></div>
我希望将此 div 中的文本更新为:
<div id="Div1"><b>Some other text.</b><br></div>
我尝试使用以下代码执行此操作,但它似乎不起作用,因为 InnerText 属性是只读的。
HtmlTextNode hNode = null;
hNode = hDoc.DocumentNode.SelectSingleNode("//div[@id='Div1']") as HtmlTextNode;
hNode.InnerText = "Some other text.";
hDoc.Save("C:\FileName.html");
我在这里做错了什么?如上所述,InnerText 是一个只读字段,尽管它在文档中写为“获取或设置”。是否有其他方法可以完成此操作?
I'm using the HTML Agility Pack to manipulate and edit a HTML document. I want to change the text in the field such as this:
<div id="Div1"><b>Some text here.</b><br></div>
I am looking to update the text within this div to be:
<div id="Div1"><b>Some other text.</b><br></div>
I've tried doing this using the following code, but it doesn't seem to be working because the InnerText property is readonly.
HtmlTextNode hNode = null;
hNode = hDoc.DocumentNode.SelectSingleNode("//div[@id='Div1']") as HtmlTextNode;
hNode.InnerText = "Some other text.";
hDoc.Save("C:\FileName.html");
What am I doing wrong here? As mentioned above, the InnerText is a read only field, although it's written in the documentation that it "gets or sets". Is there an alternate method through which this can be done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里使用的表达式是:
//div[@id='Div1']
选择div
,它不是HtmlTextNode
,因此在您的示例中,hNode
变量保存null
。InnerText
属性实际上是只读的,但HtmlTextNode
具有属性Text
,可用于设置必要的值。但在此之前您应该获取该文本节点。这可以通过以下表达式轻松完成://div[@id='Div1']//b//text()
:The expression is used here:
//div[@id='Div1']
selects thediv
, which is not aHtmlTextNode
, so thehNode
variable holdsnull
in your example.The
InnerText
property is realy read-only, butHtmlTextNode
has propertyText
which could be used to set the necessary value. But before this you should get that text node. This could be easily done with this expression://div[@id='Div1']//b//text()
: