-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.

7
  • did you try this ?: stackoverflow.com/questions/642293/… Commented Sep 6, 2017 at 17:39
  • Show us your entire XML structure. What you posted isn't enough. Commented Sep 6, 2017 at 17:40
  • Full xml contains same such things string name something and some value... Commented Sep 6, 2017 at 17:44
  • No not a duplicate of that ... That xml layout is very much different than this... Commented Sep 6, 2017 at 17:45
  • take a look at this: stackoverflow.com/questions/8898121/… Commented Sep 6, 2017 at 18:07

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@JonSkeet LINQ would work fine as well, I've updated the response to include a code sample of that approach.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.