xml字符串

Sorder 2007-08-14 10:30:25
我有一个完整的字符串如下:

"<姓名>张三</姓名>
<性别>男</性别>
<年龄>20</年龄>"

或者不完成的字符串如下:

"<姓名>张三</姓名>
<性别>男</性别>
<年龄"

现在是有没有最好最快的方法知道这个字符串是否是标准的xml格式的
...全文
179 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
BearRui 2007-08-14
  • 打赏
  • 举报
回复
还有1种就是为你的xml定义1个DTD的结构文件,然后使用XmlValidatingReader来验证,不过这个挺麻烦的,你为什么觉的catch不好了,想检查输入的字符串是否是int型的时候一般也都是使用catch啊
BearRui 2007-08-14
  • 打赏
  • 举报
回复
可以试试XmlParserContext类,应该可以,具体没用过,楼主可以看看MSDN:

string xmlFrag ="<item rk:ID='abc-23'>hammer</item> " +
"<item rk:ID='r2-435'>paint</item>" +
"<item rk:ID='abc-39'>saw</item>";

// Create the XmlNamespaceManager.
NameTable nt = new NameTable();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);
nsmgr.AddNamespace("rk", "urn:store-items");

// Create the XmlParserContext.
XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);

// Create the reader.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
XmlReader reader = XmlReader.Create(new StringReader(xmlFrag), settings, context);
Sorder 2007-08-14
  • 打赏
  • 举报
回复
难道非要用catch来捕获吗,有其它方法吗
BearRui 2007-08-14
  • 打赏
  • 举报
回复
try
{
string strXml = "你的字符串";
XmlDocument doc = new XmlDocument();
doc.LoadXml(strXml);
}catch(Exception exp){
// 出错了就表示字符串不完整
Console.Write("不是完整的XML字符串");
}
zhqs1000 2007-08-14
  • 打赏
  • 举报
回复
可以验证、
lovefootball 2007-08-14
  • 打赏
  • 举报
回复
http://support.microsoft.com/kb/318504/zh-cn

http://www.codeproject.com/cs/webservices/XmlSchemaValidator.asp
lovefootball 2007-08-14
  • 打赏
  • 举报
回复
不想try的话,你可以用正则或者XML Schemas来验证

想检查输入的字符串是否是int型的时候一般也都是使用catch啊
----》
这个肯定不能用catch
这个一般用正则或者TryParse~~~
Sorder 2007-08-14
  • 打赏
  • 举报
回复
catch有人反映耗资源了

110,567

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧