C# 验证xml的有效方法?

C# 验证xml的有效方法?,c#,xml,C#,Xml,我需要尽快进行验证,并在套接字上接收下一个xml数据 我使用这个方法来验证收到的xml数据 private validateRecievedXmlCallback() { try { XmlReader xreader = XmlReader.Create(new StringReader(xmlData)); while (xreader.Read()) ; } catch (Exception) { return false; }

我需要尽快进行验证,并在套接字上接收下一个xml数据

我使用这个方法来验证收到的xml数据

private validateRecievedXmlCallback()
{
  try
  {      
    XmlReader xreader = XmlReader.Create(new StringReader(xmlData));
    while (xreader.Read()) ;
  }
  catch (Exception)
  {
    return false;
  }

  return true;
}
但我认为这种方法不够有效。实际上我只需要检查最后一个标签

例如:

<test valueA="1" valueB="2">
   <data valueC="1" />
   <data valueC="5" />
   <data valueC="5">220</data>
</test>  //I need to check if </test> tag closed, but whats the best way to do it?

220
//我需要检查标签是否关闭,但最好的方法是什么?

任何实际面临与OP相同挑战的人:请参考,不要再考虑构建自己的XML“验证”。


编辑:添加了自动关闭标记正则表达式检查

Edit2:让regex真正做到了它应该做的事情

Edit3:编辑双重关闭标签检查(帽尖至RichardW1001)

private validateRecievedXmlCallback(IAsyncResult ar)
{
字符串SPATERN=@“^]*)\/>$”;
if(System.Text.RegularExpressions.Regex.IsMatch(xmlData,sPattern))
{
返回(真);
}
int first_occurrence=xmlData.IndexOf(“”);
int last_occurrence=xmlData.LastIndexOf(“”);
返回((第一次出现!=-1)和&(第一次出现==最后一次出现));
}

免责声明:尝试通过regex、
IndexOf()或任何其他“自制”方法“验证”XML通常是一个愚蠢的想法。只需使用适当的XML解析器。

如果您坚持使用XmlReader,您可以使用XmlReader.Skip(),它可以跳过当前元素的内容

所以

xreader.ReadStartElement(“测试”);//移动到文档根目录,如果不是,则抛出
xreader.Skip();//如果文档格式不正确,例如root没有结束标记,则抛出。

正如其他评论者已经指出的那样,除了使用XML解析器之外,没有保证XML文档格式良好的好方法。

因此,让我看看……您需要检查字符串中是否存在
,对吗?是的,但我不想使用子字符串,因为可能会发生这种情况。为什么要进行否决表决?这只是个问题?不加评论就投反对票?谢谢。@VuralAcar我比你高得多谢谢,Xml解析器正在读取每一行,但我不需要验证每个属性或元素。我只需要知道它是否被投诉。这就是为什么你有你的免责声明,但是如果末端标签是双重关闭的呢?@RichardW1001嗯……恐怕我不明白你所说的“双重关闭”是什么意思。你愿意提供一个例子吗?我知道这个故事的寓意就是使用一个合适的解析器,我想这取决于原始海报是否重要(没有具体说明),谢谢@RichardW1001修复(同时,我希望我制作的东西至少有点像C)。
private validateRecievedXmlCallback(IAsyncResult ar)
{
    string sPattern = @"^<test([^>]*) \/>$";
    if (System.Text.RegularExpressions.Regex.IsMatch(xmlData, sPattern))
    {
        return(true);
    }

    int first_occurence = xmlData.IndexOf("</test>");
    int last_occurence  = xmlData.LastIndexOf("</test>");
    return((first_occurence != -1) && (first_occurence == last_occurence));
}
xreader.ReadStartElement("test"); // moves to document root, throws if it is not <test>
xreader.Skip(); // throws if document is not well-formed, e.g. root has no closing tag.