Diego
Diego

Reputation: 2372

ASP.NET Core 6 MVC : read xml read outerxml remove tags

I am writing an ASP.NET Core 6 MVC app, and I have to read an XML with this format:

<?xml version="1.0" encoding="utf-8" ?>
<taglines common-copyright="©2007 ">
    <tagline brandID="1" brandName="BCBS" >
        <registered registered="®Registered">
        </registered>
        <copyright copyright="©2007">
        </copyright>
        <tagline2 tagline2="Data.">
        </tagline2>
    </tagline>
</taglines>

I need to read the content in tag tagline2

The way I am doing it is

private  string ReadXMLAnthemFile()
{
    string footer = "";

    XmlDocument xmlDocument = new XmlDocument();
    xmlDocument.Load(String.Concat(this.Environment.WebRootPath,"/img/TagLines.xml"));

    foreach (XmlNode node in xmlDocument.SelectNodes("taglines/tagline/tagline2"))
    {
        footer = node.OuterXml;
    }

    return footer;
}

But node.OuterXml returns the entire tag

<tagline2 tagline2="Data."></tagline2>

How can I get only the data inside the tag?

Thanks

Upvotes: 1

Views: 308

Answers (1)

marc_s
marc_s

Reputation: 755167

You don't need to read the "outer" XML - you need to reach into the XML node you've fetched, and read it's tagline2 attribute - if present.

Try something like this:

foreach (XmlNode node in xmlDocument.SelectNodes("taglines/tagline/tagline2"))
{
    if (node.Attributes["@tagline2"] != null)
    {
        footer = node.Attributes["@tagline2"].Value;
    }
}

That should get you the .Value of the tagline2 attribute of the XML node that your XPath expression matches - the value would be Data. in your case here.

Upvotes: 1

Related Questions