我在RestSharp RestRequest.Content对象中有以下XML。如何在C#中遍历它或更改为JSON以获取FULLNAME节点?
<ns1:MT_Get_Name_Res xmlns:ns1="http://hse.pd.com">
<fullname>Gandalf Elizabeth Cfieulle02</fullname>
<error>Success</error>
</ns1:MT_Get_Name_Res>
我已经尝试过的事情:
JSON - 返回一个搞砸的JSON对象,然后无法解析到我的本地对象
XmlDocument doc = new XmlDocument();
doc.LoadXml(response.Content);
string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc);
EmployeeSAPObject emp = JsonConvert.DeserializeObject<EmployeeSAPObject>(json);
C#XML解析 - fullname为null:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(response.Content); // suppose that myXmlString contains "<Names>...</Names>"
XmlNodeList xnList = xmlDoc.SelectNodes("/MT_Get_Name_Res/fullname");
foreach (XmlNode xn in xnList)
{
string fullName = xn["fullname"].InnerText;
}
这是我的EmployeeSAPObject类
public class EmployeeSAPObject
{
public string fullname { get; set; }
public string error { get; set; }
}
答案 0 :(得分:1)
您需要添加命名空间,并且希望使用XDocument而不是XmlDocument:
void Main()
{
var data = @"<ns1:MT_Get_Name_Res xmlns:ns1=""http://hse.pd.com"">
<fullname>Gandalf Elizabeth Cfieulle02</fullname>
<error>Success</error>
</ns1:MT_Get_Name_Res>";
var xdoc = XDocument.Parse(data);
Console.WriteLine(xdoc.ToString());
XNamespace ns = "http://hse.pd.com";
var result = xdoc.Element(ns + "MT_Get_Name_Res").Element("fullname").Value;
Console.WriteLine(result);
Console.ReadLine();
}
答案 1 :(得分:1)
用适当的属性装饰你的EmployeeSAPObject
并反序列化它:
[XmlRoot("MT_Get_Name_Res", Namespace = "http://hse.pd.com")]
public class EmployeeSAPObject
{
[XmlElement(Namespace="")]
public string fullname { get; set; }
[XmlElement(Namespace = "")]
public string error { get; set; }
}
然后使用它:
EmployeeSAPObject employee;
using (StringReader reader = new StringReader(response.Content))
employee = (EmployeeSAPObject)(new XmlSerializer(typeof(EmployeeSAPObject))).Deserialize(reader);
Debug.Assert(employee.fullname == "Gandalf Elizabeth Cfieulle02"); // No assert