简体   繁体   English

检查XML代码的有效性

[英]Checking the validity of XML code

Need to verify the XML: 需要验证XML:

  • Correctly tagging; 正确标记;
  • Check for the characters " > ", " < ", " & ", because they are forbidden, but allowed in &xHEX , where HEX is a number in the the 16th notation. 检查字符“ > ”,“ < ”,“ & ”,因为它们是被禁止的,但在&xHEX中是允许的,其中HEX是第16个表示法中的数字。

I think that I need to create XDocument like: 我认为我需要像这样创建XDocument

static void Main(string[] args)
{
    string s = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
               "<!--This is a comment.-->" +
               "<?xml-stylesheet href='mystyle.css' title='Compact' type='text/css'?>" +
               "<Pubs>" +
                   "<Book>" +
                       "<Title>Artifacts of Roman Civilization</Title>" +
                       "<Author>Moreno, Jordao</Author>" +
                   "</Book>" +
                   "<Book>" +
                       "<Title>Midieval Tools and Implements</Title>" +
                       "<Author>Gazit, Inbar</Author>" +
                   "</Book>" +
               "</Pubs>" +
               "<!--This is another comment.-->";//= Console.ReadLine();
    try
    {
        XDocument xDoc = XDocument.Parse(s);                
        xDoc.Save("C://22.xml");
        Console.WriteLine("Valid");
    }
    catch
    {
        Console.WriteLine("Invalid");
    }
}

Is there anything similar XDocument.Parse(s) for Framework 2 ? 是否有类似Framework 2 XDocument.Parse(s)

XDocument and entire LINQ to XML was introduced in .NET 3.5 .NET 3.5中引入了XDocument和整个LINQ to XML

If you're using .NET Framework 2.0, you should use XmlDocument : 如果使用的是.NET Framework 2.0,则应使用XmlDocument

var doc = new XmlDocument();
doc.LoadXml(s);
doc.Save("C//22.xml");

LoadXml throws XmlException when document is invalid and parsing cannot be performed. 当文档无效并且无法执行解析时, LoadXml会引发XmlException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM