c# Reading XML comment using XDocument

前端 未结 3 1377
太阳男子
太阳男子 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:37

    The Node object is the primary data type for the entire DOM.

    A node can be an element node, an attribute node, a text node, or any other of the node types explained in the "Node types" chapter.

    An XML element is everything from (including) the element's start tag to (including) the element's end tag.

         XDocument xdoc = XDocument.Load("");
           foreach (var node in xdoc.Descendants("servers").Nodes())
            {
    
                if (node is XComment)
                {
                    //THEN  READ YOUR COMMENT 
    
                }
    
            }
    
    0 讨论(0)
  • 2020-12-21 13:38

    Check node type when reading xml. If it's XComment then you are reading comment. E.g. in your case previous node of server element will be comment:

    foreach(var s in doc.Descendants("server"))
    {
        var comment = s.PreviousNode as XComment;
        if (comment != null)
            Console.WriteLine(comment.Value); // outputs "Dummy servers"
    }
    
    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
提交回复
热议问题