Sid
Sid

Reputation: 117

Change the element in the XML Response in RestAPI

I am calling a third party API from the Rest AP I am creating. The third party API always returns in XML and it looks like

 <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>

Here I should just change the name from fgfgfg to ABCD and send the entire XML as the response. I am trying the below code

    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);

But this throws error like ExceptionMessage":"Sequence contains no elements","ExceptionType":"System.InvalidOperationException"‌​,"StackTrace":" at System.Linq.Enumerable.Single[TSource]

Upvotes: 0

Views: 215

Answers (2)

kat1330
kat1330

Reputation: 5332

This approach works for me:

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

Please note I am using Root here.

Or try like this:

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

Note, Single() will throw exception if there are no elements in sequence!

Upvotes: 0

Mohit S
Mohit S

Reputation: 14064

This might do the trick for you

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

Now your object xdc is changed. You can care to save it.

Upvotes: 1

Related Questions