在RestAPI

时间:2017-01-05 01:34:15

标签: c# asp.net linq asp.net-web-api xml-parsing

我正在调用我正在创建的Rest AP中的第三方API。第三方API始终以XML格式返回,它看起来像

 <prj:prj uri="https://bh.org/api/v2/prj/V51" lid="V51" xmlns:udf="http://ge.com/ri/userdefined" xmlns:ri="http://ge.com/ri" xmlns:file="http://ge.com/ri/file" xmlns:prj="http://ge.com/ri/prj">
 <name>fgfgfg</name>
 <res uri="https://bh.org/api/v2/res/19"/>
 <udf:type name="cis"/>
 <udf:field type="String" name="ST">Cli</udf:field>
 <udf:field type="String" name="CPN">TestName</udf:field>
 <udf:field type="Numeric" name="No">1</udf:field>
 <udf:field type="String" name="CA">Do not know</udf:field>
 <udf:field type="String" name="Cto">Me</udf:field>
 <udf:field type="String" name="Site">GT</udf:field>
 </prj:prj>

这里我应该将名称从fgfgfg更改为ABCD,并将整个XML作为响应发送。我正在尝试下面的代码

    var new_Name = "ABCD";
    var response_LabURL = client_LabName.GetAsync(clarity_URL).Result;
    string responseString_LabURL = response_LabURL.Content.ReadAsStringAsync().Result;
    XDocument new_doc = XDocument.Parse(responseString_LabURL);
    var name_element = new_doc.Elements("name").Single();
    name_element.Value = new_Name;
    return Ok(new_doc);

但这会抛出ExceptionMessage":"Sequence contains no elements","ExceptionType":"System.InvalidOperationException"‌​,"StackTrace":" at System.Linq.Enumerable.Single[TSource]

之类的错误

2 个答案:

答案 0 :(得分:1)

这可能会为你做到这一点

XDocument xdc = XDocument.Load(YourXMLFile);
xdc.Descendants("name").FirstOrDefault().Value = "ABCD";

现在您的对象xdc已更改。你可以保存它。

答案 1 :(得分:0)

这种方法对我有用:

var name_element = new_doc.Root.Elements("name").Single();
name_element.Value = "new name";

请注意我在这里使用Root

或者尝试这样:

var name_element = new_doc.Descendants("name").Single();
name_element.Value = "new name";

注意,如果序列中没有元素,Single()将抛出异常!