【问题标题】:Validate xml against xsd without considering xml namesapce在不考虑 xml 命名空间的情况下针对 xsd 验证 xml
【发布时间】:2015-06-23 08:42:06
【问题描述】:

我正在使用以下代码针对 xsd 验证我的 xml。

var isXmlValid = true;
var vinListMessage = "<root xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:test/properties/v1.0\"><test12121 id=\"3\"></test></root>";
var xsdFilePath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "schema.xsd");
var schemas = new XmlSchemaSet();
schemas.Add(null, xsdFilePath);
var xmlDocument = XDocument.Parse(vinListMessage);
xmlDocument.Validate(schemas, (o, e) => { isXmlValid = false; });
Console.WriteLine(isXmlValid);

请注意上述xml中的xmlns,即urn:test/properties/v1.0。 现在在我的 xsd 中,我将 targetnamespace 作为 targetNamespace="urn:testnew/properties/v1.0",这与 xml 中的不同。

现在无论我尝试验证 xsd 的任何 xml,它总是返回 true。但如果我匹配命名空间,那么它工作正常。我想避免对命名空间的依赖。有什么建议吗?

【问题讨论】:

    标签: c# xsd linq-to-xml


    【解决方案1】:

    命名空间是元素名称的一部分,所以除了确保它们正确之外,您无能为力。

    如果所有元素的命名空间都应该相同,您可以在验证之前为所有元素设置命名空间:

    XNamespace ns = "urn:testnew/properties/v1.0";
    
    foreach (var element in xmlDocument.Descendants())
    {
        element.Name = ns + element.Name.LocalName;
    }
    
    xmlDocument.Validate(...);
    

    不幸的是,如果命名空间不匹配,那么 XML 根据架构是有效的(前提是格式正确),因为架构根本不适用于元素。验证can 会发出警告说元素未被识别,尽管不可能通过XDocument.Validate 扩展方法传递此标志(据我所知!)。

    This question 显示了另一种使用 XmlReaderXmlReaderSettings 的验证方法,如果架构无法识别元素,您可以捕获警告。

    【讨论】:

    • 感谢您的快速回答。我同意,但是为什么验证没有失败。?有什么方法可以确保命名空间不匹配是否会失败?
    • @PratikMehta 我希望添加更多内容来涵盖这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多