Reputation: 1
I need to pick data from xml in C#. Structure of xml is following:
<?xml version="1.0"?>
<xdoc version=""...>
<something>
...
</something>
<fields>
<field dimensions="" name="something else">
<ff>x</ff>
<text>something</text>
<gg>x</gg>
</field>
<field dimensions="" name="SUPPLIER_NAME">
<ff>x</ff>
<text>This is what I want</text>
<gg>x</gg>
</field>
<field dimensions="" name="something else2">
<ff>x</ff>
<text>something2</text>
<gg>x</gg>
</field>
</fields>
<something2>
...
</something2>
</xdc>
Code of query is following:
XElement root = XElement.Load(path);
IEnumerable<XElement> hodnota = from el in root.Elements("fields")
where (string)el.Attribute("name") == "SUPPLIER_NAME"
select el;
foreach (XElement in hodnota)
textBox1.Text += (string)el.Atribute("text") + Environment.NewLine;
Goal is to pick text "This is what I want" from element where attribute name is "SUPPLIER_NAME". Then send it to excel, this part is working flawlessly, but i cant find right expression so im writing to textbox for faster testing. I tried to pick string form xml, but without success so im tring this way.
Can someone please look at provided code and tell me what im doing wrong?
Thank you, Andrew
Upvotes: 0
Views: 79
Reputation: 1497
Your issue is that the attributes are under Field and not fields. Here is a sample that should work
IEnumerable<XElement> hodnota = from el in root.Elements("fields").Elements("field")
where (string)el.Attribute("name") == "SUPPLIER_NAME"
select el;
foreach (XElement el in hodnota)
Console.WriteLine(el.Element("text").Value);
or just
IEnumerable<string> hodnota = from el in root.Elements("fields").Elements("field")
where (string)el.Attribute("name") == "SUPPLIER_NAME"
select el.Element("text").Value;
foreach (string el in hodnota)
Console.WriteLine(el);
Upvotes: 1
Reputation: 34421
Use Descendants
XDocument doc = XDocument.Load(FILENAME);
List<XElement> hodnota = doc.Descendants("field").Where(el => el.Attribute("name").Value == "SUPPLIER_NAME").ToList();
Upvotes: 0
Reputation: 10068
Given the correct XML structure, this gives me desired result.
string content = File.ReadAllText(@"C:\YourFolder\Yourfile.xml");
XDocument xDoc = XDocument.Parse(content);
var supplierNameField = xDoc.Descendants("field").First(d => d.Attribute("name").Value == "SUPPLIER_NAME");
var text = supplierNameField.Element("text").Value;
Upvotes: 1