我在这个XML字符串上有一个XML读取器:
<?xml version="1.0" encoding="UTF-8" ?>
<story id="1224488641nL21535800" date="20 Oct 2008" time="07:44">
<title>PRESS DIGEST - PORTUGAL - Oct 20</title>
<text>
<p> LISBON, Oct 20 (Reuters) - Following are some of the main
stories in Portuguese newspapers on Monday. Reuters has not
verified these stories and does not vouch for their accuracy. </p>
<p>More HTML stuff here</p>
</text>
</story>
我为反序列化创建了一个xsd和相应的类。
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public class story {
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id;
[System.Xml.Serialization.XmlAttributeAttribute()]
public string date;
[System.Xml.Serialization.XmlAttributeAttribute()]
public string time;
public string title;
public string text;
}
然后,我使用xmlserializer的
Deserialize
方法创建类的实例。XmlSerializer ser = new XmlSerializer(typeof(story));
return (story)ser.Deserialize(xr);
现在,
text
的成员始终为空。如何更改story
类以便按预期解析XML?编辑:
使用xmltext不起作用,我无法控制正在解析的xml。
最佳答案
我找到了一个非常不令人满意的解决办法。
像这样改变班级(啊!)
// ...
[XmlElement("HACK - this should never match anything")]
public string text;
// ...
然后像这样更改调用代码(糟糕!)
XmlSerializer ser = new XmlSerializer(typeof(story));
string text = string.Empty;
ser.UnknownElement += delegate(object sender, XmlElementEventArgs e) {
if (e.Element.Name != "text")
throw new XmlException(
string.Format(CultureInfo.InvariantCulture,
"Unknown element '{0}' cannot be deserialized.",
e.Element.Name));
text += e.Element.InnerXml;
};
story result = (story)ser.Deserialize(xr);
result.text = text;
return result;
这是一种非常糟糕的方法,因为它破坏了封装。有更好的办法吗?
关于c# - 如何使用XmlSerializer获取XML元素的内容?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/217977/