Search code examples
c#xml.net-3.5xpathxmlreader

Using XmlReader to Read XML


I'm having some trouble using XmlReader to read an XML file. I can open and close the file okay (I think), but when it comes to parsing out the information I need, I'm a bit lost. Here is the bit of the file I need to parse:

<?xml version="1.0" encoding="UTF-8"?>
<database name="Dictionary">
  <data>
    <Translations>
      <Translation UniversalAbbv="Enu" lang="en" localization="US" unicode="0">
        <Set>
          ...
        </Set>
        <Set>
          ...
        </Set>
        <Set>
          <CaseSensitive value="0" />
          <Enums translate="1">
            <Enum_Entry ENUM_H="STOPRUN_STOP" EnumID="0" EnumString="Stop" SetID="160" />
            <Enum_Entry ENUM_H="STOPRUN_RUN" EnumID="1" EnumString="Run" SetID="160" />
            <Enum_Entry ENUM_H="STOPRUN_HOLD " EnumID="2" EnumString="Hold" SetID="160" />
          </Enums>
          <IncludeFiles_cs name="CSFile" value="StopRun.cs" />
          <IncludeFiles_h name="Header" value="NULL" />
          <IncludeFiles_java name="Java" value="NULL" />
          <SetID value="160" />
          <SetName value="Stop Run" />
          <TwoSet ENUM_H="STOPRUN_ENUM_SET" />
        </Set>
        <Set>
          ...
        </Set>
   </Translation>
  </Translations>
  </data>
</database>

I need to find where EnumID="0" or EnumID="1" (or "STOPRUN_STOP" or "STOPRUN_RUN") and respectively pull out the "Stop" or "Run" strings. Here's what I have for code so far:

static class Dictionary
{
    static private XmlReader Reader = null;

    static public void Open()
    {
        XML_Generator.Dictionary.Reader = XmlReader.Create(XML_Generator.Program.DictionaryFilename);
    }

    static public void Close()
    {
        XML_Generator.Dictionary.Reader.Close();
    }

    static public void Read()
    {
        while (Reader.Read())
        {
            Trace.TraceInformation(XML_Generator.Dictionary.Reader.ReadElementContentAsString()); // <-- This throw an error. :(
        }
    }
}

I know it's not much, but I'm a bit lost on where to go with this. Any help would be appreciated. Thanks.


Solution

  • You probably want to take a look at the XpathNavigator. The syntax of it is really easy to use, much easier than doing it with the XMLReader

    All you'd need to do to get the EnumID="1" item is //Enums/Enum_Entry[@EnumID=1]