views:

527

answers:

2

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?

A: 

Any tag within any XML document can reference a schema.

See this for examples: http://msdn.microsoft.com/en-us/library/ms757863%28VS.85%29.aspx

S.Lott
I wasn't clear - please see update.
Herb Caudill
A: 

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.

xcut
Please see the update above for clarification.
Herb Caudill
Added some more explanation under "edit".
xcut