0
我需要将XML字符串解析为c#对象。我可以使用LINQ to XML函数解析它,如果它是有效的XML像将XML字符串解析为包含自定义命名空间的对象
<root>
<child1>item on child1</child1>
<child2>item on child2</child2>
</root>
我解析它以对象的方式是:
public static T Deserialize<T>(string xml, string elementName)
{
var xDoc = XDocument.Parse(xml);
var x = xDoc.Element(elementName);
var result = Activator.CreateInstance<T>();
foreach (var node in x.Elements())
{
if (node.Elements().Any())
{
continue;
}
var properties = typeof(T).GetProperties();
var property = properties.SingleOrDefault(p => p.Name == node.Name.LocalName);
property = property ?? properties.SingleOrDefault(p => p.IsDefined(typeof(XmlElementAttribute), false) && ((XmlElementAttribute)Attribute.GetCustomAttribute(p, typeof(XmlElementAttribute))).ElementName == node.Name.LocalName);
if (property == null)
{
continue;
}
property.SetValue(result, Convert.ChangeType(node.Value, property.PropertyType));
}
return result;
}
但我不能,如果XML使用相同的方法字符串有自定义命名空间,如:
<te:array>
<te:v>tumper</te:v>
<te:v>gottag?</te:v>
<te:v>f</te:v>
</te:array>
我不知道如果有,我可以用它来解析自定义命名空间的任何方法,所有的帮助将是很有益的。
看看[的XNamespace](https://msdn.microsoft.com/en-us/library/vstudio/system.xml.linq .xnamespace(v = vs.100).aspx) – Tim
[将Linq to Xml与Xml名称空间一起使用](http://stackoverflow.com/questions/2340411/use-linq-to-xml-with-xml-命名空间) – Tim
第二个片段不是有效的Xml。它没有名称空间 - 您有一个不绑定到任何名称空间的前缀。 – Pawel