我有一个对象'AutoText‘,它是从XmlNode (从远程源检索)中使用以下ctor填充的:
public AutoText(XmlNode autoTextNode)
{
if (null == autoTextNode)
{
throw new System.Exception("Attempted to create AutoText with null autoTextNode");
}
foreach (XmlNode childNode in autoTextNode.ChildNodes)
{
string childNodeName = childNode.Name;
if (childNodeName == "Id")
{
this.AutoTextId = childNode.InnerText;
}
... snip ...
else if (childNodeName == "Autotext")
{
this.AutoTextContent = childNode.InnerText;
}
}
}有更好的方法吗?我知道我可以这样做:
this.AutoTextId = autoTextNode["Id"].InnerText;但是,如果'Id‘不存在,这可能会抛出一个空引用异常,因此您需要检查任何可选字段。实际上,在所有字段中,如果不存在强制节点,您可能需要一个特定的异常。这个解决方案看起来很难看。我相信有更好的办法,但不知道是什么!
发布于 2015-04-30 08:18:49
你可以搜索关于“序列化xml到对象”,有很多问题,主题。
给你的答案是:C# Serialize XML to Object
https://stackoverflow.com/questions/29941105
复制相似问题