簡體   English   中英

檢查XML代碼的有效性

[英]Checking the validity of XML code

需要驗證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");
    }
}

是否有類似Framework 2 XDocument.Parse(s)

.NET 3.5中引入了XDocument和整個LINQ to XML

如果使用的是.NET Framework 2.0,則應使用XmlDocument

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

當文檔無效並且無法執行解析時, LoadXml會引發XmlException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM