如何从根外的 xml 请求中读取评论

How to read a comment from xml request outside the root

对于以下示例

,在 .net web api 控制器上解析 xml 请求中的评论的好方法是什么?
<?xml version="1.0"?>
<Objects>
  <GUID-bf2401c0-ef5e-4d20-9d20-a2451a199362>
    <info job="SAVE" person="Joe" />    
    <info job="SAVE" person="Sally" />       
  </GUID-bf2401c0-ef5e-4d20-9d20-a2451a199362>
  <GUID-bf2401c0-ef5e-4d20-9d20-a583284112>
    <info job="SAVE" person="John" />    
    <info job="SAVE" person="Julie" />       
  </GUID-bf2401c0-ef5e-4d20-9d20-a5844113284112>
</Objects>
 <!--Comment about something-->

在输入流上使用正则表达式是这里唯一的选择吗?

我尝试使用 xpath /comment() 通过以下代码访问评论节点。我能够成功打印出评论节点。我认为任何行为正常的 xml 库也应该做同样的事情。

public static void main(String[] args) throws VTDException{

    String s = "<?xml version=\"1.0\"?>"+
    "<Objects>"+
      "<GUID-bf2401c0-ef5e-4d20-9d20-a2451a199362>"+
        "<info job=\"SAVE\" person=\"Joe\" /> " + 
        "<info job=\"SAVE\" person=\"Sally\" />   " +   
      "</GUID-bf2401c0-ef5e-4d20-9d20-a2451a199362>"+
      "<GUID-bf2401c0-ef5e-4d20-9d20-a583284112>"+
        "<info job=\"SAVE\" person=\"John\" />  " + 
        "<info job=\"SAVE\" person=\"Julie\" /> " +    
      "</GUID-bf2401c0-ef5e-4d20-9d20-a583284112>"+
    "</Objects>"+
     "<!--Comment about something-->";
    VTDGen vg = new VTDGen();
    vg.setDoc(s.getBytes());
    vg.parse(false);
    VTDNav vn = vg.getNav();
    AutoPilot ap = new AutoPilot(vn);
    ap.selectXPath("/comment()");

    int i=0;
    while((i=ap.evalXPath())!=-1){
        System.out.println("---->"+vn.toString(i));
    }

在 C# 中使用 LinqToXml 可以获得如下注释:

var xml = XDocument.Load("test.xml");

var comments = xml.DescendantNodes().OfType<XComment>();

foreach (var comment in comments)
    Console.WriteLine(comment.Value);

请注意,您必须使用 XDocument

如果您使用 XElement,它将仅从文档的根元素接收数据。

如果只想获取根元素后的注释,使用以下代码:

var comments = xml.Root.NodesAfterSelf().OfType<XComment>();