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