c# Reading XML comment using XDocument

前端 未结 3 1401
太阳男子
太阳男子 2020-12-21 12:53

How to read xml comment when using XDocument?

XDocument doc = XDocument.Load(\"joker.xml\");
 foreach (XElement element in doc.Descendants(\"server\"))
              


        
3条回答
  •  旧巷少年郎
    2020-12-21 13:53

    you will have to use the XmlReader.Create method and read it and switch between the nodes to indicate which node it is current reading Dont be fooled by the Create method... it reads the xml file in question but creates an instance of the XmlReader object:

    http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.create(v=vs.110).aspx

    XmlReader xmlRdr = XmlReader.Create("Joker.XML");
    // Parse the file
    while (xmlRdr.Read())
    {
        switch (xmlRdr.NodeType)
        {
            case XmlNodeType.Element:
                // Current node is an Xml Element
                break;
            case XmlNodeType.Comment:
                // This is a comment so do something with xmlRdr.value
    

    ... and so on

    PART 2 - for those who want to use LINQ (not that it makes a difference really)...

    XDocument xml = XDocument.Load("joker.xml");
    var commentNodes = from n in xml.Descendants("server")
                    where n.NodeType == XmlNodeType.Comment
                    select n;
    
    foreach(XNode node in commentNodes)
    { 
      // now you are iterating over the comments it has found
    }
    

提交回复
热议问题