Groups | Blog | Home
all groups > dotnet xml > june 2007 >

dotnet xml : How do I get the XmlSchema from an xml file


David Thielen
6/30/2007 3:50:01 PM
Hi;

If an xml file has this at the top:
<?xml version="1.0"?>
<purchaseOrder orderDate="1999-10-20"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="c:/test/po.xsd">

I need to get the XmlSchema for c:/test/po.xsd. I only need it for
noNamespaceSchemaLocation and I do not need to process the XML file itself, I
just need the schema.

I tried:
XmlSchema schema = null;
XmlDocument doc = new XmlDocument();
doc.Load(datasource.Url);
foreach (XmlSchema xsi in doc.Schemas.Schemas())
if (xsi.Namespaces.Count == 0)
{
schema = xsi;
break;
}

But doc.Schemas has 0 items. Any suggestions?

--
thanks - dave
david_at_windward_dot_net
http://www.windwardreports.com

Cubicle Wars - http://www.windwardreports.com/film.htm

David Thielen
7/1/2007 11:12:02 AM
perfect - thanks

--
thanks - dave
david_at_windward_dot_net
http://www.windwardreports.com

Cubicle Wars - http://www.windwardreports.com/film.htm




[quoted text, click to view]
Martin Honnen
7/1/2007 2:38:49 PM
[quoted text, click to view]

xsi:noNamespaceSchemaLocation is an attribute on the root element
purchaseOrder so to find the attribute value "c:/test/po.xsd" you need
to use on of the .NET XML APIs to parse out the attribute value.
For instance with XmlReader you can do

static string GetNoNamespaceSchemaLocation(string url)
{
string result = "";
using (XmlReader xmlReader = XmlReader.Create(url))
{
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
result =
xmlReader.GetAttribute("noNamespaceSchemaLocation",
"http://www.w3.org/2001/XMLSchema-instance");
break;
}
}
}
return result;
}

Then, if a schema location value is returned you can create an
XmlSchemaSet and add that schema with the location.


--

Martin Honnen --- MVP XML
AddThis Social Bookmark Button