Sometimes the processing of strings can take advantage of DOM patterns, such as the following string:
<A1>A1 value </A1><A2>A2 value </a2><a3>a3 value </a3><a4><b4 id= ' b4 ' >b4 value < /b4></a4>
To modify the value of the B4 element to "modified B4".
In addition to the regular method, you can also consider DOM operations, respectively, using the XmlDocument class and the htmlagilitypack operation.
Method 1, using the XmlDocument class:
Copy Code code as follows:
XmlDocument xmldoc = new XmlDocument ();
Xmldoc.loadxml ("<xml>" + S + "</xml>");
Xmldoc.selectsinglenode (@ "//B4"). innertext = "Modified B4";
Response.Write (Server.HTMLEncode (XMLDOC.DOCUMENTELEMENT.INNERXML));
The second sentence above is the key, because the source string may be missing a unique root element, as in this case, so wrapping a pair of labels on the outer layer can convert it into a legitimate XML document, and then the modified source text is removed with XMLDOC.DOCUMENTELEMENT.INNERXML. Of course, Method 1 is limited to the case where the source text is approximate to XML and is more canonical.
Method 2, with Htmlagilitypack:
Copy Code code as follows:
The value of the string s = @ "<A1>A1 value </a1><a2>a2 value </a2><a3>a3 </a3><a4><b4 id= ' b4 ' Value of >b4 </b4></a4> ";
HTMLDocument hxmldoc = new HTMLDocument ();
Hxmldoc.loadhtml (s);
HxmlDoc.DocumentNode.SelectSingleNode (@ "//B4"). InnerHtml = "Modified B4";
Response.Write (Server.HTMLEncode (hxmlDoc.DocumentNode.InnerHtml));
There is no need to label the package, because even if there is no unique root element, Htmlagilitypack can still parse normally.
The above two methods enlighten us to the data quantity is not big, the execution efficiency request not very high data, can organize itself into the form of label, use in the program, can also be stored in the text file. The corresponding read write operation is more convenient. The reader can further encapsulate the classes and members involved in the DOM operation and simplify the operation.