using System;
using System.Xml;
using System.Xml.Schema;
class ConsoleValidator {
private bool failed;
public bool Failed {
get { return failed; }
}
public bool ValidateXml(string xmlFilename, string schemaFilename) {
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
XmlSchemaSet schemas = new XmlSchemaSet();
settings.Schemas = schemas;
schemas.Add(null, schemaFilename);
settings.ValidationEventHandler += ValidationEventHandler;
XmlReader validator = XmlReader.Create(xmlFilename, settings);
failed = false;
try {
while (validator.Read()) { }
} catch (XmlException err) {
Console.WriteLine(err.Message);
failed = true;
} finally {
validator.Close();
}
return !failed;
}
private void ValidationEventHandler(object sender, ValidationEventArgs args) {
failed = true;
Console.WriteLine("Validation error: " + args.Message);
}
}
class MainClass {
private static void Main() {
ConsoleValidator consoleValidator = new ConsoleValidator();
bool success = consoleValidator.ValidateXml("ProductCatalog.xml", "ProductCatalog.xsd");
Console.WriteLine(success);
}
}
Month: February 2011
Set XmlReaderSettings
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
public class MainClass {
public static void Main() {
XmlDocument doc = new XmlDocument();
XmlReaderSettings rs = new XmlReaderSettings();
rs.Schemas.Add(null, "books.xsd");
rs.ValidationType = ValidationType.Schema;
XmlReader rdr = XmlReader.Create("books.xml", rs);
doc.Load(rdr);
XPathNavigator nav = doc.CreateNavigator();
if (nav.CanEdit) {
XPathNodeIterator iter = nav.Select("/bookstore/book/price");
while (iter.MoveNext()) {
iter.Current.SetTypedValue("Invalid");
}
}
doc.Save("newbooks.xml");
}
}
XML write: element, attribute, cddata, namespace and entity reference
using System;
using System.IO;
using System.Text;
using System.Xml;
public class WriteXml {
public static void Main(string [] args) {
XmlTextWriter writer = new XmlTextWriter(Console.Out);
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument(true);
writer.WriteComment(“this is a comment”);
writer.WriteStartElement(“root”);
writer.WriteAttributeString(“id”,”1″);
writer.WriteStartAttribute(“mynamespace”, “name”, “foo”);
writer.WriteString(“bar”);
writer.WriteEndAttribute();
// Write another element
writer.WriteElementString(“element1″,”some characters”);
writer.WriteStartElement(“cdataElement”);
writer.WriteAttributeString(“date”,DateTime.Now.ToString());
writer.WriteCData(“< & would choke on");
writer.WriteString("< & & & ");
writer.WriteEndElement();
// Write an empty element
writer.WriteStartElement("emptyElement");
writer.WriteEndElement();
// Write another empty element
writer.WriteStartElement("emptyElement","Empty");
writer.WriteFullEndElement();
// Write some text
writer.WriteString("One string ");
writer.WriteEntityRef("amp");
writer.WriteString(" another.");
// Close the root element
writer.WriteEndElement();
// End the document
writer.WriteEndDocument();
writer.Flush();
writer.Close();
}
}
[/csharp]
Read XML data from xml file: Node type, name
using System;
using System.IO;
using System.Xml;
class TestXMLReader
{
static void Main(string[] args)
{
TestXMLReader tstObj = new TestXMLReader();
StreamReader myStream = new StreamReader("books.xml");
XmlTextReader xmlTxtRdr = new XmlTextReader(myStream);
while(xmlTxtRdr.Read())
{
if(xmlTxtRdr.NodeType == XmlNodeType.Element
&& xmlTxtRdr.Name == "A")
{
tstObj.ProcessMyDocument(xmlTxtRdr);
}
}
}
public void ProcessMyDocument(XmlTextReader reader)
{
Console.WriteLine("Start processing:" + reader.GetAttribute("property"));
while(!(reader.NodeType == XmlNodeType.EndElement && reader.Name == "B")
&& reader.Read()) {
if(reader.NodeType == XmlNodeType.Element && reader.Name == "C") {
Console.WriteLine("itemcode:" + reader.GetAttribute("c"));
}
}
}
}
/*
<books>
<A property="a">
<B>text</B>
<C c="aaa" >textg</C>
<D>99999</D>
</A>
</books>
*/
XmlNodeType Text
using System;
using System.Xml;
using System.IO;
using System.Text;
class MainClass {
private static void Main() {
FileStream fs = new FileStream(“products.xml”, FileMode.Create);
XmlWriter w = XmlWriter.Create(fs);
w.WriteStartDocument();
w.WriteStartElement(“products”);
w.WriteStartElement(“product”);
w.WriteAttributeString(“id”, “1001”);
w.WriteElementString(“productName”, “Gourmet Coffee”);
w.WriteElementString(“productPrice”, “0.99”);
w.WriteEndElement();
w.WriteStartElement(“product”);
w.WriteAttributeString(“id”, “1002”);
w.WriteElementString(“productName”, “Blue China Tea Pot”);
w.WriteElementString(“productPrice”, “102.99”);
w.WriteEndElement();
w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
fs.Close();
fs = new FileStream(“products.xml”, FileMode.Open);
XmlReader r = XmlReader.Create(fs);
while (r.Read()) {
if (r.NodeType == XmlNodeType.Element) {
Console.WriteLine(“<" + r.Name + ">“);
if (r.HasAttributes) {
for (int i = 0; i < r.AttributeCount; i++) {
Console.WriteLine(" ATTRIBUTE: " +
r.GetAttribute(i));
}
}
} else if (r.NodeType == XmlNodeType.Text) {
Console.WriteLine(" VALUE: " + r.Value);
}
}
}
}
[/csharp]
Get XML Nodes in a Specific XML Namespace
using System;
using System.Xml;
public class SelectNodesByNamespace {
private static void Main() {
XmlDocument doc = new XmlDocument();
doc.Load("Order.xml");
XmlNodeList matches = doc.GetElementsByTagName("*","http://mycompany/OrderML");
foreach (XmlNode node in matches) {
Console.Write(node.Name + " ");
foreach (XmlAttribute attribute in node.Attributes) {
Console.Write(attribute.Value + " ");
}
}
}
}
Set Xml Node Value
using System;
using System.Text;
using System.Xml;
//GNU General Public License version 2 (GPLv2)
//http://cbasetest.codeplex.com/license
public class MainClass{
public static void SetXmlNodeValue(XmlNode xmlae, object value)
{
SetXmlNodeValue(xmlae, value, string.Empty);
}
public static void SetXmlNodeValue(XmlNode xmlae, string value)
{
XmlDocument ownerDocument = xmlae.OwnerDocument;
foreach (XmlNode node in xmlae.ChildNodes)
{
if (node.NodeType == XmlNodeType.Text)
{
node.Value = value;
}
}
}
public static void SetXmlNodeValue(XmlNode xmlae, object value, string defaultStr)
{
string str = defaultStr;
if (value != null)
{
str = value.ToString();
}
if (str != null)
{
SetXmlNodeValue(xmlae, str.ToString());
}
}
}

