0

I am using a StreamReader to read a XML file.
From that, how to get particular content in the file?

C# code I'm using:

using (StreamReader streamreader = new StreamReader(inputxmlfile))
{
    string doc = streamreader.ReadLine();
    while (doc != null)
    {
        if (content.Contains("sxnum"))
        {
            // How to get the 'sxnum' attribute value?
        }
        doc = streamreader.ReadLine();
    }
}

Here what the XML file looks like:

<?xml version="1.0" encoding="UTF-8"?>
    <catalog>
    <cd nominee ="1 2 First" sxnum="63828910">
        <title company="Grammy" price="10.20">1999 Grammy Nominees</title>
        <artist all="type">Many</artist>
        <country>USA</country>
        .....
</catalog>

The desired output in this case is:

63828910
Orace
  • 7,822
  • 30
  • 45
  • What have you tried ? RegEx, XPath ? – Orace Dec 06 '22 at 15:38
  • There is both `System.Xml.XmlDocument` and `System.Xml.Linq.XDocument` (and their associated/related types within their respective namespaces) provided by .NET. Choose whatever is more appropriate. The latter, XDocument, is perhaps the slightly better choice due to its public API lending itself to Linq-ish programming styles (as also indicated by its namespace name). –  Dec 06 '22 at 15:48
  • Duplicate of https://stackoverflow.com/questions/3750678 – Orace Dec 06 '22 at 15:48

1 Answers1

1

If the XML document is bigger and you want to process it without loading it all into memory at once, you can use the XmlReader class which can move through the xml document node by node without loading the whole document into memory.

using (StreamReader streamReader = new StreamReader(inputxmlfile))
{
    // Create the xmlReader using the streamReader as a source
    using (XmlReader xmlReader = XmlReader.Create(streamReader))
    {
        // While there are element nodes with the name "cd", go to the next cd element
        while (xmlReader.ReadToFollowing("cd"))
        {
            // Get the value of the sxnum attribute at the current element
            // and output it when present
            string sxnum = xmlReader.GetAttribute("sxnum");
            if (!string.IsNullOrEmpty(sxnum))
            {
                Console.WriteLine(sxnum);
            }
        }
    }
}
NineBerry
  • 26,306
  • 3
  • 62
  • 93