如何在 C# 中根据 DTD 验证 XML 文档?

发布于 2024-08-09 12:58:23 字数 572 浏览 5 评论 0原文

我不想做任何花哨的事情,我只想确保文档有效,如果无效则打印错误消息。 Google 向我指出了 this,但 XmlValidatingReader 似乎已过时(至少 MonoDevelop 是这么说的)我)。

编辑:我正在尝试迈赫达德的建议,但遇到了麻烦。我想我已经掌握了大部分内容,但我在任何地方都找不到 OnValidationEvent 。我从哪里获取 OnValidationEvent?

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.DTD;
settings.ValidationEventHandler += new ValidationEventHandler(/*trouble is here*/);
XmlReader validatingReader = XmlReader.Create(fileToLoad, settings);

I don't want to do anything fancy, I just want to make sure a document is valid, and print an error message if it is not. Google pointed me to this, but it seems XmlValidatingReader is obsolete (at least, that's what MonoDevelop tells me).

Edit: I'm trying Mehrdad's tip, but I'm having trouble. I think I've got most of it, but I can't find OnValidationEvent anywhere. Where go I get OnValidationEvent from?

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.DTD;
settings.ValidationEventHandler += new ValidationEventHandler(/*trouble is here*/);
XmlReader validatingReader = XmlReader.Create(fileToLoad, settings);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

极度宠爱 2024-08-16 12:58:23

而不是创建 XmlValidatingReader 直接,您应该构建适当的 XmlReaderSettings 对象 并将其作为参数传递给 XmlReader。 Create方法

var settings = new XmlReaderSettings { ValidationType = ValidationType.DTD };
settings.ValidationEventHandler += new ValidationEventHandler(OnValidationEvent);
var reader = XmlReader.Create("file.xml", settings);

其余不变。

PS OnValidationEvent 是您声明的用于处理验证事件的方法的名称。显然,如果您不想订阅由 XmlReader 引发的验证事件,则可以删除该行。

Instead of creating XmlValidatingReader class directly, you should construct an appropriate XmlReaderSettings object and pass it as an argument to the XmlReader.Create method:

var settings = new XmlReaderSettings { ValidationType = ValidationType.DTD };
settings.ValidationEventHandler += new ValidationEventHandler(OnValidationEvent);
var reader = XmlReader.Create("file.xml", settings);

The rest is unchanged.

P.S. OnValidationEvent is the name of the method you declare to handle validation events. Obviously, you can remove the line if you don't want to subscribe to validation events raised by the XmlReader.

行至春深 2024-08-16 12:58:23
var messages = new StringBuilder();
var settings = new XmlReaderSettings { ValidationType = ValidationType.DTD };
settings.ValidationEventHandler += (sender, args) => messages.AppendLine(args.Message);
var reader = XmlReader.Create("file.xml", settings);

if (messages.Length > 0)
{
    // Log Validation Errors
    // Throw Exception
    // Etc.
}

ValidationEventHandler

Lambda 表达式

类型推断

var messages = new StringBuilder();
var settings = new XmlReaderSettings { ValidationType = ValidationType.DTD };
settings.ValidationEventHandler += (sender, args) => messages.AppendLine(args.Message);
var reader = XmlReader.Create("file.xml", settings);

if (messages.Length > 0)
{
    // Log Validation Errors
    // Throw Exception
    // Etc.
}

ValidationEventHandler

Lambda Expressions

Type Inference

戏舞 2024-08-16 12:58:23

我在 DTD 验证中提到了这个示例。
https:// learn.microsoft.com/en-us/dotnet/api/system.xml.xmlreadersettings.dtdprocessing?view=netcore-3.1#input

此示例具有无效的 DTD XML,我已将其更正如下。

<!--XML file using a DTD-->
<!DOCTYPE store [
  <!ELEMENT store (item)*> 
  <!ELEMENT item (name,dept,price)>
  <!ATTLIST item type CDATA #REQUIRED ISBN CDATA 
#REQUIRED>
  <!ELEMENT name (#PCDATA)>
  <!ELEMENT dept (#PCDATA)>
  <!ELEMENT price (#PCDATA)>]>
<store>
  <item type="supplies"  ISBN="2-3631-4">
    <name>paint</name>
    <dept>1</dept>
    <price>16.95</price>
  </item>
</store>

I've referred to this example on DTD validation.
https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlreadersettings.dtdprocessing?view=netcore-3.1#input

This example has invalid DTD XML, which I've corrected as below.

<!--XML file using a DTD-->
<!DOCTYPE store [
  <!ELEMENT store (item)*> 
  <!ELEMENT item (name,dept,price)>
  <!ATTLIST item type CDATA #REQUIRED ISBN CDATA 
#REQUIRED>
  <!ELEMENT name (#PCDATA)>
  <!ELEMENT dept (#PCDATA)>
  <!ELEMENT price (#PCDATA)>]>
<store>
  <item type="supplies"  ISBN="2-3631-4">
    <name>paint</name>
    <dept>1</dept>
    <price>16.95</price>
  </item>
</store>
最后的乘客 2024-08-16 12:58:23

完整描述:

  1. 在 Visual Studio .NET 中,创建一个新的 Visual C# 控制台应用程序
    名为 ValidateXml 的项目。在开头添加两个 using 语句
    Class1.cs如下:

    使用 System.Xml; // 对于 XmlTextReader 和 XmlValidatingReader
    使用 System.Xml.Schema; // 用于XmlSchemaCollection(稍后使用)
    
  2. Class1.cs 中,在
    Main 方法的开始如下:

    private static bool isValid = true; // 如果发生验证错误,
                                             // 在中将此标志设置为 false
                                             // 验证事件处理程序。 
    
  3. 创建一个 XmlTextReader 对象以从文本中读取 XML 文档
    Main 方法中创建一个 XmlValidatingReader
    按如下方式验证此 XML 数据:

    XmlTextReader r = new XmlTextReader("C:\\MyFolder\\ProductWithDTD.xml");
    XmlValidatingReader v = new XmlValidatingReader(r);
    
  4. XmlValidatingReader 对象的 ValidationType 属性
    指示所需的验证类型(DTD、XDR 或
    架构)。将此属性设置为 DTD,如下所示:

    v.ValidationType = ValidationType.DTD;
    
  5. 如果发生任何验证错误,验证读取器会生成一个
    验证事件。添加以下代码来注册验证
    事件处理程序(您将实现 MyValidationEventHandler
    步骤7)中的方法:

    v.ValidationEventHandler += 
       新的 ValidationEventHandler(MyValidationEventHandler);
    
  6. 添加以下代码来读取并验证 XML 文档。如果有的话
    发生验证错误,调用 MyValidationEventHandler
    解决错误。此方法将 isValid 设置为 false(请参阅步骤 8)。
    验证后可以检查isValid的状态来查看是否
    文件有效或无效。

    while (v.Read())
    {
       // 可以在这里添加代码来处理内容。
    }
    v.关闭();
    
    // 检查文档是否有效。
    if (有效)
       Console.WriteLine("文档有效");
    别的
       Console.WriteLine("文档无效");
    
  7. Main 方法之后编写 MyValidationEventHandler 方法,如下所示
    如下:

    public static void MyValidationEventHandler(对象发送者, 
                                                ValidationEventArgs 参数) 
    {
       有效=假;
       Console.WriteLine("验证事件\n" + args.Message);
    }
    

构建并运行应用程序。应用程序应报告 XML 文档有效。
例如:
在 Visual Studio .NET 中,修改 ProductWithDTD.xml 使其无效(例如,删除 M soliman 元素)。
再次运行应用程序。您应该收到以下错误消息:

Validation event
Element 'Product' has invalid content. Expected 'ProductName'.
An error occurred at file:///C:/MyFolder/ProductWithDTD.xml(4, 5).
Document is invalid

full description:

  1. In Visual Studio .NET, create a new Visual C# Console Application
    project named ValidateXml. Add two using statements to the beginning
    of Class1.cs as follows:

    using System.Xml;        // for XmlTextReader and XmlValidatingReader
    using System.Xml.Schema; // for XmlSchemaCollection (which is used later)
    
  2. In Class1.cs, declare a boolean variable named isValid before the
    start of the Main method as follows:

    private static bool isValid = true;      // If a validation error occurs,
                                             // set this flag to false in the
                                             // validation event handler. 
    
  3. Create an XmlTextReader object to read an XML document from a text
    file in the Main method, and then create an XmlValidatingReader to
    validate this XML data as follows:

    XmlTextReader r = new XmlTextReader("C:\\MyFolder\\ProductWithDTD.xml");
    XmlValidatingReader v = new XmlValidatingReader(r);
    
  4. The ValidationType property of the XmlValidatingReader object
    indicates the type of validation that is required (DTD, XDR, or
    Schema). Set this property to DTD as follows:

    v.ValidationType = ValidationType.DTD;
    
  5. If any validation errors occur, the validating reader generates a
    validation event. Add the following code to register a validation
    event handler (you will implement the MyValidationEventHandler
    method in Step 7):

    v.ValidationEventHandler += 
       new ValidationEventHandler(MyValidationEventHandler);
    
  6. Add the following code to read and validate the XML document. If any
    validation errors occur, MyValidationEventHandler is called to
    address the error. This method sets isValid to false (see Step 8).
    You can check the status of isValid after validation to see if the
    document is valid or invalid.

    while (v.Read())
    {
       // Can add code here to process the content.
    }
    v.Close();
    
    // Check whether the document is valid or invalid.
    if (isValid)
       Console.WriteLine("Document is valid");
    else
       Console.WriteLine("Document is invalid");
    
  7. Write the MyValidationEventHandler method after the Main method as
    follows:

    public static void MyValidationEventHandler(object sender, 
                                                ValidationEventArgs args) 
    {
       isValid = false;
       Console.WriteLine("Validation event\n" + args.Message);
    }
    

Build and run the application. The application should report that the XML document is valid.
e.g.:
In Visual Studio .NET, modify ProductWithDTD.xml to invalidate it (for example, delete the <AuthorName>M soliman</AuthorName> element).
Run the application again. You should receive the following error message:

Validation event
Element 'Product' has invalid content. Expected 'ProductName'.
An error occurred at file:///C:/MyFolder/ProductWithDTD.xml(4, 5).
Document is invalid
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文