2014-02-11 66 views
0

需要驗證XML:檢查的XML代碼有效性

  • 正確標記;
  • 檢查字符「>」,「<」,「&」,因爲它們是禁止的,但允許在&xHEX中,其中HEX是第16個記號中的數字。

我認爲我需要創建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"); 
    } 
} 

有什麼相似XDocument.Parse(s)Framework 2

回答

1

XDocument和整個的LINQ to XML在.net 3.5

介紹如果您使用的.NET Framework 2.0,你應該使用XmlDocument

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

LoadXml拋出XmlException當文件是無效的,解析無法執行。