2013-01-02 119 views
3

我对XML像这样XML反序列化和XPath?

​​

凡公民名称是对方节点内的复杂类型。 (这是从第三方集成,我创建一个适配器收到的XML)

我不感兴趣,有一个子类型,因为在我的班级我试图反序列化成我宁愿有。

public class Party 
{ 
    public string FirstName { get; set; } 
    public string LastName {get;set;} 

} 

因此,而不是有我的类定义的XML代表什么具体的定义,我可以装饰性的东西,如XPath的,如。

[XmlElement("\CitizenName\CitizenNameForeName")] 
public string FirstName {get;set;} 

要樱桃从xml中选择信息到类中包含我感兴趣的数据?

从第三方收到的XML非常冗长,我只对特定方面感兴趣。一种选择是创建一个XMLDocument并使用XPath和一种转换方法手动映射到我的类,但是我想如果有中间解决方案,我会问这个问题吗?

回答

0

最后,我建立了自己的属性来做我想做的事情。因此,一个自定义属性采用XPath路径...

[System.AttributeUsage(System.AttributeTargets.Property)] 
public class PathToXmlNode : System.Attribute 
{ 
    public string Path { get; set; } 

    public PathToXmlNode(string path) 
    { 
     this.Path = path; 
    } 
} 

其次是装饰属性。(为了简化省略命名空间)

  [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); 
       } 

      } 
     } 

这是一个很好的起点,但如果别人看到的这是一个可行的解决方案的中介,你需要知道它需要适应非简单数据类型。这就是我现在要做的事情!

0

一种选择是使用XSLT转换将传入XML解析为与您的类匹配的s格式。

+0

我对XSLT并不是很了不起,但是之前我曾经涉猎过,因为XML的数量已经拉回来了,所以我不确定这将会是一个可行的方法。但是,谢谢你的建议。 – Chris