peter
peter

Reputation: 8662

how to take value from xml file in .net c#

i have an xml file i want to get inner text by using linq.Xml is as shown below

<?xml version="1.0" encoding="utf-8" ?>
<testObject class="LN" version="16A" distName="CEL-1" id="456" xmlns="kaml20.xsd">
  <p name="rcc">424</p>
  <p name="kcc">02</p>
  <p name="testname">testobject</p>
</testObject>

and i did the following code with no result

private static string GetvalueNokia(XElement pin, string val)
{
    string fname="";
    try
    {
        //string location = pin.Descendants("cellName").Single().Value;

        //return pin
        //.Descendants("p")
        //.FirstOrDefault(x => x.Attributes().Any(a => a.Value.ToUpper() == val.ToUpper())).Value;
        ////.Attribute("value").Value;

        var data = from atts in pin.Elements("name")
                   select new
                   {
                       cell= (string)atts.Element("name")
                   };
     }
}

EDIT my pin is as shwon below

<testObject class="LN" version="16A" distName="CEL-1" id="456" xmlns="kaml20.xsd">
  <p name="cellName">testname</p>
  <p name="rcc">424</p>
  <p name="kcc">02</p>
</testObject>

Upvotes: 0

Views: 119

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

It looks like you want to get the inner text of the xml node which has a particular value in the name attribute, if that's correct, you can try the following code:

var data = (from node in pin.Descendants("name")
            where node.Attribute("name") !=null &&  node.Attribute("name").Value == value
           select new
           {
              AttributeValue = node.Attribute("name").Value,
              InnerText = node.Value
           });

We need to first filter the nodes which have attribute name and in combination with that it contains the value which is provided as input.

and if you want to do case-insenstive comparison of the input parameter in xml nodes attribute, then you can use String.Compare like:

String.Equals(node.Attribute("name").Value, value,StringComparison.OrdinalIgnoreCase) 

and if pin is the element from which you are trying to get the name attribute value, then just call the Attribute method on it with the attribute name as input and access the Value property like:

private static string GetvalueNokia(XElement pin, string val)
{ 
  return pin.Attribute("name")?.Value;
}

Hope it helps!

Upvotes: 1

Related Questions