-2

I have an XML file which contains following lines

<string name="accept">Accept</string>
<string name="action_settings">Settings</string>
<string name="app_name">Val</string>

How can I get value of app_name string which is Val in C#. I tried XML parser but it doesn't work.

Sach
  • 10,091
  • 8
  • 47
  • 84
  • did you try this ?: https://stackoverflow.com/questions/642293/how-do-i-read-and-parse-an-xml-file-in-c –  Sep 06 '17 at 17:39
  • Show us your entire XML structure. What you posted isn't enough. – Sam Axe Sep 06 '17 at 17:40
  • Full xml contains same such things string name something and some value... – Kaustubh Patange Sep 06 '17 at 17:44
  • No not a duplicate of that ... That xml layout is very much different than this... – Kaustubh Patange Sep 06 '17 at 17:45
  • take a look at this: https://stackoverflow.com/questions/8898121/select-elements-with-the-name-attribute-name-in-special-xml-structure – Sparrow Sep 06 '17 at 18:07
  • "That xml layout is very much different than this" - the expectation is that you do research and amend existing solutions as required. Stack Overflow isn't about handing you answers on a plate without you doing research. – Jon Skeet Sep 06 '17 at 18:14
  • @KaustubhPatange _it doesn't work_ is not a good way to ask a question. You should show what you did, and _in what way_ it doesn't work. Then we can help. – Sach Sep 06 '17 at 18:16

1 Answers1

0

You can use XmlDocument and an XPath statement in the SelectSingleNode method to retrieve this information. Here is an example:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
var accept = doc.SelectSingleNode("//string[@name='accept']").InnerText;
var actionSettings = doc.SelectSingleNode("//string[@name='action_settings']").InnerText;
var appName = doc.SelectSingleNode("//string[@name='app_name']").InnerText;

Here is a tutorial on XPath syntax: https://www.w3schools.com/xml/xpath_syntax.asp

UPDATE: @jon-skeet suggested using LINQ. Should you choose to do that, your code might look something like:

var element = XElement.Parse(xml);
var accept = element.Descendants("string").Where(x => x.Attribute("name").Value == "accept").Select(x => x.Value).FirstOrDefault();
var actionSettings = element.Descendants("string").Where(x => x.Attribute("name").Value == "action_settings").Select(x => x.Value).FirstOrDefault();
var appName = element.Descendants("string").Where(x => x.Attribute("name").Value == "app_name").Select(x => x.Value).FirstOrDefault();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
David Kujawski
  • 319
  • 1
  • 7
  • I'd *strongly* encourage using LINQ to XML instead of XmlDocument, and only using XPath when you really need to - I see no benefit in doing that here. The result is fiddly and error-prone code. – Jon Skeet Sep 06 '17 at 18:15
  • @JonSkeet LINQ would work fine as well, I've updated the response to include a code sample of that approach. – David Kujawski Sep 06 '17 at 18:28