gpt4 book ai didi

c# - "Type ' http ://www. w3.org/2000/09/xmldsig# :SignatureType ' is not declared" in XmlDocument. 验证(...)

转载 作者:太空宇宙 更新时间:2023-11-03 15:27:26 26 4
gpt4 key购买 nike

我有这个非常简单的 XSD 架构

<?xml version = "1.0" encoding = "UTF-8"?>
<schema xmlns = "http://www.w3.org/2001/XMLSchema"
targetNamespace = "http://my.domain/xmlschemas/message"
xmlns:mmm = "http://my.domain/xmlschemas/message"
xmlns:ds = "http://www.w3.org/2000/09/xmldsig#"
xmlns:xsd = "http://www.w3.org/2001/XMLSchema"
elementFormDefault = "qualified">
<import namespace = "http://www.w3.org/2000/09/xmldsig#" schemaLocation = "xmldsig-core-schema.xsd"/>
<element name = "message">
<complexType>
<sequence>
<element name = "Signature" type = "ds:SignatureType" minOccurs = "0" maxOccurs = "unbounded"/>
</sequence>
</complexType>
</element>
</schema>

存储为我的 Visual Studio 2010 C# 项目以及 xmldsig-core-schema.xsd 的嵌入式资源,我从 www.w3.org/TR/xmldsig- 下载核心/xmldsig-核心-schema.xsd.

我想根据此 XSD 模式验证我的文档。我的文档:

<?xml version="1.0" encoding="UTF-8"?>
<message xmlns="http://my.domain/xmlschemas/message">
</message>

我使用 XmlDocument.Validate(...) 方法以这种方式进行验证:

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(inputStream); //XML document loads correctly...

Assembly myAssembly = Assembly.GetExecutingAssembly();
using (Stream schemaStream = myAssembly.GetManifestResourceStream("XmlSigTest.Resources.message.xsd"))
{
XmlSchema schema = XmlSchema.Read(schemaStream, null);
doc.Schemas.Add(schema); //XSD schema loads correctly
}

bool ok = true;
doc.Validate((s, e) => //throws Exception!!!
{
ok = false;
});

此代码在 doc.Validate(...) 中抛出异常,消息为:Type 'http://www.w3.org/2000/09/xmldsig#:SignatureType ' 未声明。但是,Visual Studio XML 编辑器中没有警告或错误,我可以在 Visual Studio XML 架构资源管理器中看到 SignatureType。为什么抛出这个异常?我该怎么办?

最佳答案

我自己解决了这个问题。我的 XSD 的这一行运行不正常:

<import namespace = "http://www.w3.org/2000/09/xmldsig#" schemaLocation = "xmldsig-core-schema.xsd"/>

我认为 doc.Validate(...) 会自动下载或查找所有引用的外部模式。 (xmldsig-core-schema.xsd 在我的例子中)。好吧……它不会。

我不得不手动将引用的模式添加到 doc.Schemas 中,从那以后就没问题了。

结果代码:

XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.Load(inputStream);

Assembly myAssembly = Assembly.GetExecutingAssembly();
foreach (string resource in new string[] {"message.xsd", "xmldsig-core-schema.xsd"}) {
using (Stream schemaStream = myAssembly.GetManifestResourceStream("XmlSigTest.Resources." + resource))
{
XmlSchema schema = XmlSchema.Read(schemaStream, null);
doc.Schemas.Add(schema);
}
}

bool ok = true;
doc.Validate((s, e) =>
{
ok = false;
});

关于c# - "Type ' http ://www. w3.org/2000/09/xmldsig# :SignatureType ' is not declared" in XmlDocument. 验证(...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34679548/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com