demo stack
demo stack

Reputation: 103

Getting XML data from the string

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?

Upvotes: 1

Views: 395

Answers (2)

Dan Field
Dan Field

Reputation: 21661

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();

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503859

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);

Upvotes: 3

Related Questions