C# XML反序列化和XPath?
我有这样的XmlC# XML反序列化和XPath?,c#,xml,serialization,C#,Xml,Serialization,我有这样的Xml <pda:Party> ...Snip.... <pda:CitizenName> <pda:CitizenNameTitle>MR</pda:CitizenNameTitle> <pda:CitizenNameForename>John</pd
<pda:Party>
...Snip....
<pda:CitizenName>
<pda:CitizenNameTitle>MR</pda:CitizenNameTitle>
<pda:CitizenNameForename>John</pda:CitizenNameForename>
<pda:CitizenNameSurname>Wayne</pda:CitizenNameSurname>
</pda:CitizenName>
.....Snip...
</pda:Party>
因此,我可以用XPath之类的东西来修饰属性,而不是将我的类定义作为XML表示内容的具体定义,例如
[XmlElement("\CitizenName\CitizenNameForeName")]
public string FirstName {get;set;}
从xml中挑选信息到包含我感兴趣的数据的类中
从第三方收到的xml非常详细,我只对特定方面感兴趣。一个选项是使用XPath和转换方法手动创建一个XMLDocument并映射到我的类,但我想我会问,万一有中间解决方案呢?一个选项是使用XSLT转换将传入的XML解析为与类匹配的s格式。最后,我设置了自己的属性来做我想让它做的事情。因此,采用XPath路径的自定义属性
[System.AttributeUsage(System.AttributeTargets.Property)]
public class PathToXmlNode : System.Attribute
{
public string Path { get; set; }
public PathToXmlNode(string path)
{
this.Path = path;
}
}
然后是一处装饰过的房子。。(为了简单起见,省略了名称空间)
然后,当我想填充这个类时,我调用了下面的方法
var type = typeof(T);
foreach (var property in type.GetProperties())
{
var attributes = property.GetCustomAttributes(typeof(PathToXmlNode), true);
if (attributes != null && attributes.Length > 0)
{
//this property has this attribute assigned.
//get the value to assign
var xmlAttribute = (PathToXmlNode)attributes[0];
var node = doc.SelectSingleNode(xmlAttribute.Path, nmgr);
if (node != null && !string.IsNullOrWhiteSpace(node.InnerText))
{
dynamic castedValue;
if (property.PropertyType == typeof(bool))
{
castedValue = Convert.ToBoolean(node.InnerText);
}
...Snip all the casts....
else
{
castedValue = node.InnerText;
}
//we now have the node and it's value, now set it to the property.
property.SetValue(obj, castedValue, System.Reflection.BindingFlags.SetProperty, null, null, System.Globalization.CultureInfo.CurrentCulture);
}
}
}
这是一个很好的起点,但是,如果其他人认为这是一个可行的中介解决方案,那么您需要知道,它将需要适应非简单数据类型。这就是我现在要做的 我并不擅长XSLT,我以前也涉猎过,但是由于get的XML量太大,我不相信随着时间的推移,它会是一种可行的方法。但是谢谢你的建议。
[PathToXmlNode("Party[1]/CitizenName/CitizenNameForename")]
public string FirstName { get; set; }
var type = typeof(T);
foreach (var property in type.GetProperties())
{
var attributes = property.GetCustomAttributes(typeof(PathToXmlNode), true);
if (attributes != null && attributes.Length > 0)
{
//this property has this attribute assigned.
//get the value to assign
var xmlAttribute = (PathToXmlNode)attributes[0];
var node = doc.SelectSingleNode(xmlAttribute.Path, nmgr);
if (node != null && !string.IsNullOrWhiteSpace(node.InnerText))
{
dynamic castedValue;
if (property.PropertyType == typeof(bool))
{
castedValue = Convert.ToBoolean(node.InnerText);
}
...Snip all the casts....
else
{
castedValue = node.InnerText;
}
//we now have the node and it's value, now set it to the property.
property.SetValue(obj, castedValue, System.Reflection.BindingFlags.SetProperty, null, null, System.Globalization.CultureInfo.CurrentCulture);
}
}
}