0

I am trying to read a certain section from an xml file in C#. I tried using this code here but I get a compiler error under the Text in XmlNodeType.Text but the weird thing is it comes up with intellisense and gives the same error with everything else like Element ,Comment etc.. what am I missing?

XmlTextReader reader = new XmlTextReader(xmlDoc);
List<string> paths = new List<string>();
while (reader.Read())
{
    if (reader.NodeType == XmlNodeType.Element && reader.Name == "Paths")
        foreach(XmlNodeType.Text aa in reader.ReadInnerXml())
            paths.Add(aa);
}
reader.Close();

XML file

<Config>
    <Paths>
      <Input>C:\</Input>
      <Output>C:\</Output>
      <Log>\Logs</Log>
    </Paths>

    <SystemOwnerRoles>
      <Supplier>SUPPLIER</Supplier>
      <Mop>MOP</Mop>
    </SystemOwnerRoles>
</Config>
WhatsThePoint
  • 3,395
  • 8
  • 31
  • 53

1 Answers1

1

XmlNodeType is an enum. XmlNodeType.Text is a value, not a type, but you're trying to use it as the type of the aa variable. Furthermore ReaderInnerXml() returns a string, so it's not clear how you expect to iterate over it.

Do you have to use XmlTextReader for this? Almost all XML work is simpler using LINQ to XML. For example, this is all I think you need:

var paths = XDocument.Load(xmlDoc)
                     .Descendants("Paths")
                     .Elements()
                     .Select(element => (string) element)
                     .ToList();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • no i dont have to use `XMLTextReader` its just what i came across first never used XML before and not that great at `LINQ` but ill give this a try – WhatsThePoint Apr 07 '17 at 08:54
  • @WhatsThePoint: It's *much* easier to use LINQ to XML than `XmlReader` - and if you're uncomfortable with LINQ in general, I strongly suggest you try to improve, as it's *incredibly* useful. – Jon Skeet Apr 07 '17 at 08:59
  • i got an exception when running this, it said data at root level is invalid at line 1 position 1 am i writing my xml wrong? – WhatsThePoint Apr 07 '17 at 08:59
  • @WhatsThePoint: I'd assumed that `xmlDoc` was the string that you'd loaded already. If it's actually the filename, you need `XDocument.Load` instead. I'll edit my answer. (Hint: this is where a [mcve] would have removed any ambiguity. I should have checked the `XmlTextReader` documentation to see which constructor you were calling, but the clearer you can make your question, the better.) – Jon Skeet Apr 07 '17 at 09:00