简体   繁体   中英

Extract the XML value in to string c#

I have the string which has the XML tag like

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<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">
    <name>Administrative Lab</name>
    <billing-address>
        <street></street>
        <city></city>
        <state></state>
        <country></country>
        <postalCode></postalCode>
        <institution></institution>
        <department></department>
    </billing-address>
    <shipping-address>
        <street></street>
        <city></city>
        <state></state>
        <country></country>
        <postalCode></postalCode>
        <institution></institution>
        <department></department>
    </shipping-address>
    <udf:field type="String" name="Account ID">adm</udf:field>
    <website></website>
</lab:lab>" 

In order to just extract the value adm ie any value between the <udf> tag should I be using the XDocument or the XmlDocument.I understand I can use XDocument.Parse but this I am not sure how to give the tag name. I tried below

  XDocument new_doc = XDocument.Parse(new_responseString);
  var a = from udf in new_doc.Descendants("udf") select udf.Value;

But there can be additional udf fields in future so what will I be checking should be name="Account ID" and I am not sure how to do this

How can I retrieve this?

You can use Attribute method for retrieving attribute's value of XElement .

var udf = "http://ghjhjhj.com/ri/userdefined";
var new_doc = XDocument.Parse(new_responseString);
var fieldValues = doc.Descendants(udf + "field")
                   .Where(field => field.Attribute("name").Value.Equals("Account ID"))
                   .Select(field => field.Value);

foreach (var value in fieldValues)
{
    Console.WriteLine(value);
}

If you need only one value then use FirstOrDefault method

var fieldValue = 
    doc.Descendants(udf + "field")
       .FirstOrDefault(field => field.Attribute("name").Value.Equals("Account ID"))
       .Value;

But be aware - this query will throw exception of there no elements with attribute name = "Account ID"

Probably this might do the trick for you

XNamespace laburi = "http://iuiuu.com/ri/lab";
XNamespace udfuri = "http://ghjhjhj.com/ri/userdefined";
XDocument xdoc = XDocument.Load("some.txt");
var a = xdoc.Elements(laburi + "lab").Elements(udfuri + "field").FirstOrDefault().Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM