Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically attach XML files to XSD schema in Visual Studio?

I just discovered the beauty of Visual Studio's automatic XSD schema generation.*

Is there an easy way to have VS automatically attach files with particular names to existing XSD schema? So if I have myconfig.xml files scattered throughout a project (or several projects) I would want them to always validate against myconfig.xsd, rather than have to open each XML file and associate it manually. Is this possible?

* For those who aren't familiar: Open XML file, XML/Create Schema, and it creates a nice schema file based on what it sees in your XML file. You can then attach the same XSD to another XML file by opening that file and choose XML/Schemas and choosing the appropriate schema from your project. You then get intellisense and validation on all your element and attribute names, required elements and attributes, etc.


Update: I think I wasn't really clear.

When I create a new web.config file anywhere in a project, I don't manually assign a schema to it. There's no namespace specified within the XML. Nevertheless Visual Studio automatically knows to use DotNetConfig.xsd:

XML Schemas dialog screenshot

Presumably Visual Studio has a mapping somewhere that assigns files named web.config to DotNetConfig.xsd.

Now, suppose I want all files named DbSchema.xml to automatically use a schema I created called DbSchema.xsd. Is there a way to do that?

like image 403
Herb Caudill Avatar asked Dec 28 '09 22:12

Herb Caudill


Video Answer


2 Answers

If your schemas are in the same workspace (not necessarily project) as your XML files, Visual Studio will automatically use them for auto-complete and validation, as long as your files have a namespace declaration.

You don't even need to put in a schemaLocation attribute.

Try the following:

  • Double click an XML file to open it
  • In the menu item "XML" that now appears dynamically, click "Schemas...". This will show you the current mapping from namespaces to schemas.

To check if it's working, try to put an open angle bracket somewhere, it should suggest element names.

Edit: this will also work with XML files without namespaces, but then you probably have to add a new schema catalog to %Install%\Xml\Schemas, as described here. Near the bottom, it describes how to use the "Association" element to associate schemas by extension.

like image 111
xcut Avatar answered Oct 12 '22 10:10

xcut


Any tag within any XML document can reference a schema.

See this for examples: http://msdn.microsoft.com/en-us/library/ms757863(VS.85).aspx

like image 43
S.Lott Avatar answered Oct 12 '22 08:10

S.Lott