473,386 Members | 1,775 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Sample code for how to load an XMLDocument with an XML file while simultaneously validating it against an XSD, AND how to read and search that same validated XML file.

Hi all,

Spent WAAAYYY too much time trying to figure this out because there's
not many good examples out there, so in the interest of sparing y'all
from suff'rin same, I've pasted it into eternity for you. Works like a
charm.

(I know, I know, I love you too)

Sean

//C# code

string filename = "whateverYouCalledYourXMLAndXSDfile"
XmlDocument loggingMessagesDefinition = new XmlDocument()
MessageDataXmlFile = filename + ".xml";
MessageDataXsdFile = filename + ".xsd";

// initialize the validation objects
XmlSchemaCollection myXmlSchemas = new XmlSchemaCollection();
myXmlSchemas.Add("http://tempuri.org/LoggingMessagesDefinition.xsd",
new XmlTextReader(MessageDataXsdFile));
XmlValidatingReader myXmlValidatingReader =
new XmlValidatingReader(new XmlTextReader(MessageDataXmlFile));
myXmlValidatingReader.Schemas.Add(myXmlSchemas);
myXmlValidatingReader.ValidationType = ValidationType.Schema;

//load and validate at same time. Throws exception if bad data
loggingMessagesDefinition.Load(myXmlValidatingRead er);

// set up namespace manager to enable XML searching
nsmgr = new XmlNamespaceManager(loggingMessagesDefinition.Name Table);
//chose df to represent default
nsmgr.AddNamespace("df","http://tempuri.org/LoggingMessagesDefinition.xsd");

//example of how to search and extract from XML doc
//notice the df prefixes to indicate the default namespace
string type = "2";
string messageSeverity =
loggingMessagesDefinition.DocumentElement.SelectSi ngleNode(
"descendant::df:LogMessage[df:ID='" + type +
"']", nsmgr).SelectSingleNode("df:Severity",
nsmgr).InnerText; // should return 'Not Good' as a result

// here's the XML file

<?xml version="1.0" encoding="UTF-8" ?>
<Data xmlns="http://tempuri.org/LoggingMessagesDefinition.xsd">
<LogMessage>
<ID>1</ID>
<Description>Unknown memory error</Description>
<Class>Memory</Class>
<Severity>Error</Severity>
<Action>Phone appropriate personnel</Action>
</LogMessage>
<LogMessage>
<ID>2</ID>
<Description>Out of memory</Description>
<Class>Memory</Class>
<Severity>Not Good</Severity>
<Action>Phone appropriate personnel</Action>
</LogMessage>
</Data>
// and here's the XSD file I used, little overly detailed for this
example but typically these can be auto-generated anyway (In visual
studio, look at you XML file in 'Data' mode and then right click the
grid and choose generate schema, which pumps out an XSD for ya)
<?xml version="1.0" ?>
<xs:schema id="Data"
targetNamespace="http://tempuri.org/LoggingMessagesDefinition.xsd"
xmlns:mstns="http://tempuri.org/LoggingMessagesDefinition.xsd"
xmlns="http://tempuri.org/LoggingMessagesDefinition.xsd"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
attributeFormDefault="qualified" elementFormDefault="qualified">
<xs:element name="Data" msdata:IsDataSet="true"
msdata:EnforceConstraints="False">
<xs:complexType>
<xs:choice maxOccurs="unbounded">
<xs:element name="LogMessage">
<xs:complexType>
<xs:sequence>
<xs:element name="ID" type="xs:positiveInteger" minOccurs="0" />
<xs:element name="Description" type="xs:string" minOccurs="0" />
<xs:element name="Class" minOccurs="0" msdata:Ordinal="2">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Memory" />
<xs:enumeration value="Thread" />
<xs:enumeration value="File" />
<xs:enumeration value="Data" />
<xs:enumeration value="Network" />
<xs:enumeration value="Database" />
<xs:enumeration value="Application" />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Severity" minOccurs="0" msdata:Ordinal="3">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Error" />
<xs:enumeration value="Warning" />
<xs:enumeration value="Status" />
<xs:enumeration value="Metric" />
<xs:enumeration value="Debug" />
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="Action" minOccurs="0" msdata:Ordinal="4">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Phone appropriate personnel" />
<xs:enumeration value="None" />
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>

May 5 '06 #1
0 1536

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: srijit | last post by:
Hello, Here is an example code of xml writer in Python+PythonNet, Ironpython and Boo. The codes look very similar. Regards, Srijit Python + PythonNet: import CLR
5
by: serge calderara | last post by:
dear all, I have benn going through a .net possibility such as amanging XMLDocument and xml transmorf function. In that set of features I am really swimming deep under the water, I have nearly...
2
by: Nikhil Patel | last post by:
Hi all, I use a Word Xml Template in ASP.Net application. Basically when a user clicks on a certain button on a web form, I open the template using XmlDocument.Load method; replace some strings in...
6
by: Brian Miller | last post by:
I've been constructing an ASP.Net application using the 1.1 framework, and have been using Web Matrix for development purposes. Now that my application is near completion, I wanted to see if I can...
3
by: ek03 | last post by:
I have a web application that saves/loads XML documents. On occasion, an error is logged on the call to XmlDocument.Load: "process cannot access the file <filepath here> because it is being used by...
4
by: ss | last post by:
hi, can anybody gives me a sample code where the sql injection attack is validated. how can i do that in business logic layer and pass the error to the presentation tier I want the sample...
3
by: josh.kuo | last post by:
Sorry about the subject, I can't think of a better one. I recently wrote some PHP classes that I think might be of interest to this group. Since I have been reaping the benefits of reading news...
232
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first...
1
by: engwar | last post by:
The title says it all. How do I use XMLDocument.Validate() against a DTD. In all my Googling about this I only find examples of how to validate an XMLReader or XmlValidatingReader against a DTD....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.