None
None

Reputation: 5670

Read data from string XML

My situation is like this, I have a xml data in string format.

<?xml version="1.0" encoding="utf-16"?>
<Tree AllowNodeEditing="True" ShowLineImages="False" CheckBoxes="True" EnableAjaxSkinRendering="False" AutoPostBackOnCheck="True" AutoPostBack="True">
 <Node Text="IMG_1468.JPG" Value="../../CMS/Images/Fotogalerie/548/IMG_1468.JPG" Checked="True" Selected="True" tekst="Afbeelding IMG_1468.JPG" thumb="../../CMS/Images/Thumbs/548/IMG_1468.JPG" />

from above string i need to select 'Value' of each node and store it in a datatable.How can i achieve this..

Upvotes: 1

Views: 15708

Answers (5)

HW90
HW90

Reputation: 1983

One way is to convert the string to xmldoc, than you can read the xmldoc byusing LINQ:

String to XML:

    String rawXml =
              @"<root>
                    <person firstname="Riley" lastname="Scott" />
                    <person firstname="Thomas" lastname="Scott" />
                </root>";
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(rawXml);



var lv1s = from lv1 in xdoc.Descendants("person")
           select new { 
               firstname = lv1.Attribute("firstname").Value,
                lastname = lv1.Attribute("lastname").Value
           };

Upvotes: 3

gliderkite
gliderkite

Reputation: 8928

I would use XElement class.

XElement xmlTree = XElement.Parse("yourXMLString");

And then you can analyze each element using XElement methods, for example:

foreach (XElement el in xmlTree.Elements())
   // Do what you want with el

You could also query it:

<Tree>
  <Node Text="IMG_1468.JPG" Value="../../CMS/Images/Fotogalerie/548/IMG_1468.JPG" />
</Tree>

string yourValue = xmlTree.Elements("Node")
                      .Where(x => (string) x.Attribute("Text") == "IMG_1468.JPG")
                      .Select(x => (string) x.Attribute("Value"))
                      .Single();

Upvotes: 3

Tung
Tung

Reputation: 5444

XDocument doc = XDocument.Parse(xml);
var values = from element in doc.XPathSelectElements("/Tree/Node")
                     where element.Attribute("Value") != null
                     select (element.Attribute("Value").Value);

Upvotes: 1

Zaki
Zaki

Reputation: 5600

XmlNodeList elementList = doc.GetElementsByTagName("*");
for (int i = 0; i < elementList.Count; i++)
{
    string attrVal = elementList[i].Attributes["Value"].Value;
}

Upvotes: 1

ionden
ionden

Reputation: 12786

Use Linq to XML:

XDocument doc = XDocument.Parse(xml_string);
var values = (from f in doc.Elements().Descendants()
              select f.Attribute("Value").Value).ToArray();

Upvotes: 2

Related Questions