| 利斌's profileThe time when I was youn...PhotosBlogLists | Help |
|
February 06 How to serialize a property of an object as Xml CData in .net.Net framework provides the infrastructure which is able to serialize an instance of a class into a xml file. It makes serializing object simple. You just place some attributes followed by the read/write property of a class, like this: public class TestClass [XmlElement("Name", typeof(string))] And then you just need to invoke the method "Serialize" of the class "XmlSerializer" and pass an instance of the class, you would get the xml file that you want. But if you assign a value which contains some special characters, such as "<", ">" and so forth, you would find all these characters would be replaced with & something in result xml file. If you want to reserve the special characters, you maybe remember that there is a type named "CDATA" in xml. All characters in cdata section would be reserved as their original style. Like the following snippet: <TestClass>
</TestClass> Unfortunately, I cannot give the xml element a type named "CdataSection" something. In the other word, the following code is wrong: [XmlElement("Name"), typeof(XmlCDataSection)] Then how can I do this? After searching internet and msdn, I find I must implement the interface "IXmlSerializable" for the class, it means I must control all serialization action, including all members which need to serialize. Ok. Just like the following: public class TestClass: IXmlSerializable #region IXmlSerializable interface implementation
#endregion How to use XPath functionAbout last year, I used XPath, but I did not use functions of XPath. Today, I met an issue that needs to get nodes which contain specific content. This issue looks like wildchar * and % in sql. But in XPath, no these wildchar. So I search the internet and find the resolution in w3schools. There are some embed functions in XPath. I noticed one function named "contains" which looks like what I wanted. But how to use it? There is not any example for it. I had to take tries. Finally, I found the correct syntax, like the following:
Xml file:
<root>
<book>Harry Poter</book>
</root>
For example, I want to get the books which name contain the string "Harry" from the xml file. Then the XPath should be like:
"root/book[contains(text(),'Harry']"
Here, I used two xpath functions named "contains" and "text". |
|
|