Use Dom to manipulate a string

  • 2020-05-16 06:47:53
  • OfStack

Sometimes strings can be handled in Dom mode, such as the following string:

< a1 > The value of the a1 < /a1 > < a2 > The value of the a2 < /a2 > < a3 > The value of the a3 < /a3 > < a4 > < b4 id='b4' > The value of the b4 < /b4 > < /a4 >

To change the value of the b4 element to "modified b4".

In addition to the regular method, you can also consider Dom operations, using the XmlDocument class and HtmlAgilityPack operations, respectively.

Method 1, using the XmlDocument class:
 
XmlDocument xmlDoc = new XmlDocument(); 
xmlDoc.LoadXml("<xml>" + s + "</xml>"); 
xmlDoc.SelectSingleNode(@"//b4").InnerText = " The modified b4"; 
Response.Write(Server.HtmlEncode(xmlDoc.DocumentElement.InnerXml)); 

The second sentence above is the key. Since the source string may lack the root element of only 1, as in this example, wrapping the 1 pair of tags in the outer layer will convert it to a valid xml document, and then the modified source text will be retrieved using xmlDoc.DocumentElement.InnerXml. Of course, method 1 is limited to situations where the source text is similar to xml and is relatively canonical.

Method 2, using HtmlAgilityPack:
 
string s = @"<a1>a1 The value of the </a1><a2>a2 The value of the </a2><a3>a3 The value of the </a3><a4><b4 id='b4'>b4 The value of the </b4></a4>"; 
HtmlDocument hxmlDoc = new HtmlDocument(); 
hxmlDoc.LoadHtml(s); 
hxmlDoc.DocumentNode.SelectSingleNode(@"//b4").InnerHtml = " The modified b4"; 
Response.Write(Server.HtmlEncode(hxmlDoc.DocumentNode.InnerHtml)); 

There is no need to wrap it with a label, because HtmlAgilityPack can parse normally without a single root element.

The above two methods suggest that we can organize the data with small data volume and low execution efficiency into the form of label, which can be used in the program or stored in a text file. The corresponding read-write operation is more convenient. The reader can further encapsulate the classes and members involved in the Dom operation to simplify the operation.

Related articles: