xml – 当引用的模式文件位于不同的项目/程序集中时,如何在VS中指定XSD schemaLocation属性?

前端之家收集整理的这篇文章主要介绍了xml – 当引用的模式文件位于不同的项目/程序集中时,如何在VS中指定XSD schemaLocation属性?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
编辑请参阅下面的解决方案/编辑

我有一个包含两个项目的Visual Studio解决方案.

> Project 1(称为ReferencedProject)包含XML模式文件(ReferencedSchema.xsd).
> Project 2(称之为MainProject)包含ReferencedProject作为参考. MainProject还有一个模式文件(MainSchema.xsd).

MainSchema.xsd包含以下代码

@H_404_8@<?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>

因为ReferencedSchema.xsd不在同一个文件夹中(它甚至不在同一个项目中),所以我收到错误消息“ReferencedSchema.xsd无法解析”.说得通.

如果我编辑xs:include元素到这个…

@H_404_8@<xs:include schemaLocation="../../ReferencedProject/Data/ReferencedSchema.xsd" />

……错误消失了.但是,请注意我已经提供了一个相对路径,该路径只能在我的解决方案的文件夹层次结构中工作.当我在编辑器中查看模式时,这很好,但在编译项目时却不是很好.如果我在编译后查看我的“bin”文件夹,则文件夹层次结构完全不同(两个xsd文件实际上最终位于同一文件夹中).

我尝试使用Visual Studio的“将现有项目添加链接功能解决此问题,将ReferencedSchema.xsd文件的快捷方式放在与我的主模式文件相同的文件夹中,但这不起作用. XSD验证器显然无法假装链接是实际文件.

所以,我的问题是似乎没有任何uri我可以提供的schemaLocation在两种情况下都是有效的(在解决方案资源管理器中和运行时).有没有人有什么建议?

谢谢!

编辑

我决定这样做:

@H_404_8@<xs:include schemaLocation="../../ReferencedProject/Data/ReferencedSchema.xsd" />

只要我在Visual Studio中查看内容,在运行我的代码时就不正确,这是正确的.

为了使它在运行时也能工作,我使用正确的相对引用动态替换schemaLocation,如下所示:

@H_404_8@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; }

我选择了这个解决方案,因为无论我在Visual Studio中查看XML和XSD文件还是运行/调试我的应用程序,现在一切都能正常运行.

XSD仅支持URI位置,而不支持路径位置.这意味着file:/// C:/path/to/VS/Projects/ReferencedProject/Data/ReferencedSchema.xsd有效,但不是../../ReferencedProject/Data/ReferencedSchema.xsd.

猜你在找的XML相关文章