1
string xml = "<ABCProperties> <Action> Yes | No | None </Action><Content>
<Header> Header Text </Header><Body1> Body Paragraph 1 </Body1>
<BodyN> Body Paragraph N</BodyN></Content><IsTrue> true | false </IsTrue>
<Duration> Long | Short </Duration></ABCProperties>";

Here, from the XML, I want to extract certain strings. First is the Header Text in the Header tags.

When, I try

XDocument doc = XDocument.Parse(xml);
var a = doc.Descendants("Header").Single();

I get variable a = <Header> Header Text </Header>. How can I get only var a = Header Text?

Secondly, I want to get text of all the Body paragrahs. It can be either Body1, Body2 or BodyN. How can I get contents of all Body tags.

Can anyone help me with this?

1
  • Your question doesn't make very much sense at the moment, even after I've edited the formatting a bit. A variable isn't <Header> Header Text </Header> - it's just a variable. If you convert the variable to a string, you might get "<Header> Header Text </Header> but you should clarify that that's what you mean. Commented Jan 19, 2016 at 16:23

2 Answers 2

3

You're asking for the Header element - so that's what it gives you. If you only want the text of that, you can just use:

var headerText = doc.Descendants("Header").Single().Value;

To find all the body tags, just use a Where clause:

var bodyText = doc.Descendants()
                  .Where(x => x.Name.LocalName.StartsWith("Body"))
                  .Select(x => x.Value);
Sign up to request clarification or add additional context in comments.

Comments

0

Start with just getting the content node, which is what you really want, and then iterate through its children checking if it's a body or header node, and use the string.Trim() function to get rid of leading/trailing whitespace.:

string xml = @"<ABCProperties> <Action> Yes | No | None </Action><Content>
<Header> Header Text </Header><Body1> Body Paragraph 1 </Body1>
<BodyN> Body Paragraph N</BodyN></Content><IsTrue> true | false </IsTrue>
<Duration> Long | Short </Duration></ABCProperties>";

XDocument doc = XDocument.Parse(xml);

XElement content = doc.Root.Element("Content");

foreach (XElement el in content.Elements())
{
    string localName = el.Name.LocalName;

    if (localName == "Header")
    {
        Console.WriteLine(localName + ": " + el.Value.Trim());
    }
    else if (localName.StartsWith("Body"))
    {
        Console.WriteLine(localName + ": " + el.Value.Trim());
    }
}

Console.ReadKey();

2 Comments

How can I do foreach loop from ABCProperties here ? Not from Content.
Just change the loop - foreach (XElement el in doc.Root.Descendants()) is probably what you want in that case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.