2012-01-16 53 views
3

我需要尽可能快地验证并接收套接字上的下一个xml数据。有效的方法来验证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? 
+0

所以,让我看看......你需要检查字符串中是否存在'',对吧? – vzwick 2012-01-16 21:25:00

+0

是的,但我不想使用子字符串,因为它可能发生 Racooon 2012-01-16 21:25:59

+0

为什么选择投票?这只是一个问题? – Racooon 2012-01-16 21:27:09

回答

6

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

所以

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. 

正如其他评论者已经指出的那样,有一个保证XML文档的区别在于使用XML解析器良好性的好方法。

+0

所以upvoted。您的答案应该有复选标记。 – vzwick 2012-01-16 22:04:08

1

实际上任何人都面临着同样的挑战,因为OP:参考the answer by Sven Künzler和从来没有想过再打造自己的XML“验证”。


编辑:新增自闭标签的正则表达式检查。

EDIT2:制造正则表达式实际上做什么它应该

EDIT3:编辑双重封闭的标记检查(帽尖到RichardW1001

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)); 
} 

免责声明:它通常是通过正则表达式,IndexOf()或任何其他“本土”方法尝试和“验证”XML的愚蠢想法。只需使用适当的XML解析器即可。

+0

谢谢,Xml解析器正在读取每一行,但我不需要验证每个属性或元素。我只需要知道它是否符合。 – Racooon 2012-01-16 21:34:31

+0

这就是您拥有免责声明的原因,但如果结束标记是双关闭的,那么该怎么办? – RichardW1001 2012-01-16 21:53:43

+0

@ RichardW1001呃......恐怕我不明白“双关”是什么意思。你愿意提供一个例子吗? – vzwick 2012-01-16 21:55:44