我有一个像
这样的字符串new_responseString ="<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<lab:lab xmlns:udf=\"http://ghjhjhj.com/ri/userdefined\" xmlns:ri=\"http://kjkj.com/ri\" xmlns:lab=\"http://iuiuu.com/ri/lab\" uri=\"https://hhjjhjhj.org/api/v2/labs/1\">\n <name>Administrative Lab</name>\n <billing-address>\n <street></street>\n <city></city>\n <state></state>\n <country></country>\n <postalCode></postalCode>\n <institution></institution>\n <department></department>\n </billing-address>\n <shipping-address>\n <street></street>\n <city></city>\n <state></state>\n <country></country>\n <postalCode></postalCode>\n <institution></institution>\n <department></department>\n </shipping-address>\n <udf:field type=\"String\" name=\"Account ID\">adm</udf:field>\n <website></website>\n</lab:lab>\n"
为了只提取值adm,即标记<udf></udf>
var new_response = new_client.GetAsync(new_Uri).Result;
string new_responseString = new_response.Content.ReadAsStringAsync().Result;
var new_doc = XDocument.Parse(new_responseString);
var udf = "http://ghjhjhj.com/ri/userdefined";
var udfValue = doc.Descendants(udf + "field").FirstOrDefault(field => field.Attribute("name").Value.Equals("Account ID")).Value;
return udfValue;
但这引发了异常
System.Xml.XmlException:':'字符,十六进制值0x3A,不能包含在名称中
我还有一个问题,而不是像ReadAsStringAsync()
中的string new_responseString = new_response.Content.ReadAsStringAsync().Result
这样的字符串读取响应,这可以用API返回响应的原始格式进行检索。
答案 0 :(得分:1)
使用命名空间的正确方法是使用XNamespace
:
XNamespace ns = "http://ghjhjhj.com/ri/userdefined";
var udfValue = new_doc.Descendants(ns + "field").FirstOrDefault(field => field.Attribute("name").Value.Equals("Account ID")).Value;