dev*_*xer 8 xml xsd visual-studio
编辑请参阅下面的解决方案/编辑
我有一个包含两个项目的Visual Studio解决方案.
MainSchema.xsd包含以下代码:
<?xml version="1.0"?>
<xs:schema
xmlns="main"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:tns="main"
targetNamespace="main"
elementFormDefault="qualified">
<xs:include schemaLocation="ReferencedSchema.xsd" />
...
</xs:schema>
Run Code Online (Sandbox Code Playgroud)
因为ReferencedSchema.xsd不在同一个文件夹中(它甚至不在同一个项目中),所以我收到错误消息"ReferencedSchema.xsd无法解析".说得通.
如果我编辑xs:include元素到这个...
<xs:include schemaLocation="../../ReferencedProject/Data/ReferencedSchema.xsd" />
Run Code Online (Sandbox Code Playgroud)
......错误消失了.但是,请注意我已经提供了一个相对路径,该路径只能在我的解决方案的文件夹层次结构中工作.当我在编辑器中查看模式时,这很好,但在编译项目时却不是很好.如果我在编译后查看我的"bin"文件夹,则文件夹层次结构完全不同(两个xsd文件实际上最终位于同一文件夹中).
我尝试使用Visual Studio的"将现有项目添加为链接"功能来解决此问题,将ReferencedSchema.xsd文件的快捷方式放在与我的主模式文件相同的文件夹中,但这不起作用.XSD验证器显然无法假装链接是实际文件.
所以,我的问题是似乎没有任何uri我能为schemaLocation提供在两种情况下都有效(在解决方案资源管理器中和运行时).有没有人有什么建议?
谢谢!
编辑
我决定这样做:
<xs:include schemaLocation="../../ReferencedProject/Data/ReferencedSchema.xsd" />
Run Code Online (Sandbox Code Playgroud)
这是正确的,只要我在Visual Studio中查看内容,在运行我的代码时不正确.
为了使它在运行时也能工作,我使用正确的相对引用动态替换schemaLocation,如下所示:
public class UriReplacingXmlValidator
{
public virtual XDocument Validate(
string dataFolderName,
string baseDataFolderName,
string xmlFileName,
string schemaFileName,
string baseSchemaFileName)
{
string rootFolderPath = Environment.CurrentDirectory + Path.DirectorySeparatorChar;
string dataFolderPath = rootFolderPath + Path.DirectorySeparatorChar + dataFolderName;
string baseDataFolderPath = rootFolderPath + Path.DirectorySeparatorChar + baseDataFolderName;
string xmlPath = dataFolderPath + Path.DirectorySeparatorChar + xmlFileName;
string schemaPath = dataFolderName + Path.DirectorySeparatorChar + schemaFileName;
string baseSchemaPath = baseDataFolderName + Path.DirectorySeparatorChar + baseSchemaFileName;
XDocument xmlDocument = XDocument.Load(xmlPath);
XDocument schemaDocument = XDocument.Load(schemaPath);
ResetBaseSchemaLocation(schemaDocument, baseSchemaPath);
XmlValidator validator = new XmlValidator();
bool isValid = validator.Validate(xmlDocument, schemaDocument);
if (isValid)
return xmlDocument;
else
return null;
}
protected virtual void ResetBaseSchemaLocation(XDocument schemaDocument, string baseSchemaPath)
{
XNamespace ns = "http://www.w3.org/2001/XMLSchema";
XAttribute attribute = schemaDocument.Element(ns + "schema").Element(ns + "redefine").Attribute("schemaLocation");
attribute.Value = baseSchemaPath;
}
Run Code Online (Sandbox Code Playgroud)
我选择了这个解决方案,因为无论我是在Visual Studio中查看XML和XSD文件还是运行/调试我的应用程序,现在一切都能正常运行.
T0x*_*ode 10
XSD仅支持URI位置,而不支持路径位置.这意味着它file:///C:/path/to/VS/Projects/ReferencedProject/Data/ReferencedSchema.xsd是有效的,但不是../../ReferencedProject/Data/ReferencedSchema.xsd.
| 归档时间: |
|
| 查看次数: |
38524 次 |
| 最近记录: |