Read comments with XDocument

StewartBW 505 Reputation points
2024-04-08T02:18:46.1866667+00:00

Hey

This is the xml I have:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--Comments Are Just Here-->
<TheOnlyNode>
  <ID>15</ID>
  ...
</TheOnlyNode>

There's only one single comment in the root, after loading this xml with XDocument, how to read that sole comment?

Thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,378 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,604 questions
{count} votes

Accepted answer
  1. KOZ6.0 5,215 Reputation points
    2024-04-08T04:13:50.7433333+00:00
    Imports System.Xml
    
    Module Module1
    
        Sub Main()
            Const xmlString As String =
                    "<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes""?>" &
                    "<!--Comments Are Just Here-->" &
                    "<TheOnlyNode>" &
                    "  <ID>15</ID>" &
                    "</TheOnlyNode>"
    
            Dim xmlDoc = New XmlDocument()
            xmlDoc.LoadXml(xmlString)
    
            ' only one
            Dim oneNode As XmlNode = xmlDoc.SelectSingleNode("//comment()")
            If oneNode IsNot Nothing Then
                Console.WriteLine(oneNode.Value)
            End If
    
            ' multiple comments
            For Each node As XmlNode In xmlDoc.SelectNodes("//comment()")
                Console.WriteLine(node.Value)
            Next
    
            Console.ReadKey()
    
        End Sub
    
    End Module
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful