XML工具操作类,很强大

该类主要是针对XML文件的操作方法,其封装了XML文件的一些常用的操作方法,代码非常严谨,值得学习和使用

 

ContractedBlock.gif ExpandedBlockStart.gif Code
using System;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Net;
using System.CodeDom;

namespace CSharpRecipes
{
    
public class XML
    {
        
#region "15.1 Reading and Accessing XML Data in Document Order"
        
static void Indent(int level)
        {
            
for (int i = 0; i < level; i++)
                Console.Write(
" ");
        }

        
public static void AccessXml()
        {
            
string xmlFragment = "<?xml version='1.0'?>" +
                
"<!-- My sample XML -->" +
                
"<?pi myProcessingInstruction?>" +
                
"<Root>" + 
                
"<Node1 nodeId='1'>First Node</Node1>" +
                
"<Node2 nodeId='2'>Second Node</Node2>" +
                
"<Node3 nodeId='3'>Third Node</Node3>" +
                
"</Root>";

            
byte[] bytes = Encoding.UTF8.GetBytes(xmlFragment);
            
using (MemoryStream memStream = new MemoryStream(bytes))
            {
                XmlReaderSettings settings 
= new XmlReaderSettings();
                
// check for any illegal characters in the XML
                settings.CheckCharacters = true;

                
using (XmlReader reader = XmlReader.Create(memStream, settings))
                {
                    
int level = 0;
                    
while (reader.Read())
                    {
                        
switch (reader.NodeType)
                        {
                            
case XmlNodeType.CDATA:
                                Indent(level);
                                Console.WriteLine(
"CDATA: {0}", reader.Value);
                                
break;
                            
case XmlNodeType.Comment:
                                Indent(level);
                                Console.WriteLine(
"COMMENT: {0}", reader.Value);
                                
break;
                            
case XmlNodeType.DocumentType:
                                Indent(level);
                                Console.WriteLine(
"DOCTYPE: {0}={1}",
                                    reader.Name, reader.Value);
                                
break;
                            
case XmlNodeType.Element:
                                Indent(level);
                                Console.WriteLine(
"ELEMENT: {0}", reader.Name);
                                level
++;
                                
while (reader.MoveToNextAttribute())
                                {
                                    Indent(level);
                                    Console.WriteLine(
"ATTRIBUTE: {0}='{1}'",
                                        reader.Name, reader.Value);
                                }
                                
break;
                            
case XmlNodeType.EndElement:
                                level
--;
                                
break;
                            
case XmlNodeType.EntityReference:
                                Indent(level);
                                Console.WriteLine(
"ENTITY: {0}", reader.Name);
                                
break;
                            
case XmlNodeType.ProcessingInstruction:
                                Indent(level);
                                Console.WriteLine(
"INSTRUCTION: {0}={1}",
                                    reader.Name, reader.Value);
                                
break;
                            
case XmlNodeType.Text:
                                Indent(level);
                                Console.WriteLine(
"TEXT: {0}", reader.Value);
                                
break;
                            
case XmlNodeType.XmlDeclaration:
                                Indent(level);
                                Console.WriteLine(
"DECLARATION: {0}={1}",
                                    reader.Name, reader.Value);
                                
break;
                        }
                    }
                }
            }
        }
        
#endregion
    
        
#region "15.2 Reading XML on the Web"    
        
public static void ReadXmlWeb()
        {
            
// This requires you set up a virtual directory pointing
            
// to the sample.xml file included with the sample code
            
// prior to executing this
            string url = "http://localhost/xml/sample.xml";
            
using (XmlReader reader = XmlReader.Create(url))
            {
                
while (reader.Read())
                {
                    
switch (reader.NodeType)
                    {
                        
case XmlNodeType.Element:
                            Console.Write(
"<{0}>", reader.Name);
                            
break;
                    }
                }
            }
        }
        
#endregion
    
        
#region "15.3 Querying the Contents of an XML Document"    
        
public static void QueryXml()
        {
            
string xmlFragment = "<?xml version='1.0'?>" +
                
"<Clue>" + 
                
"<Participant type='Perpetrator'>Professor Plum</Participant>" +
                
"<Participant type='Witness'>Colonel Mustard</Participant>" +
                
"<Participant type='Witness'>Mrs. White</Participant>" +
                
"<Participant type='Witness'>Mrs. Peacock</Participant>" +
                
"<Participant type='Witness'>Mr. Green</Participant>" +
                
"</Clue>";
            
using (StringReader reader = new StringReader(xmlFragment))
            {
                
// Instantiate an XPathDocument using the StringReader.  
                XPathDocument xpathDoc = new XPathDocument(reader);

                
// get the navigator
                XPathNavigator xpathNav = xpathDoc.CreateNavigator();

                
// set up the query looking for the married female participants 
                
// who were witnesses
                string xpathQuery =
                    
"/Clue/Participant[attribute::type='Witness'][contains(text(),'Mrs.')]";
                XPathExpression xpathExpr 
= xpathNav.Compile(xpathQuery);

                
// get the nodeset from the compiled expression
                XPathNodeIterator xpathIter = xpathNav.Select(xpathExpr);

                
// write out the nodes found (Mrs. White and Mrs.Peacock in this instance)
                while (xpathIter.MoveNext())
                {
                    Console.WriteLine(xpathIter.Current.Value);
                }
            }
        }
        
#endregion
    
        
#region "15.4 Validating a static XML stream"    
        
public static void ValidateXml()
        {
            
// create XSD schema collection with book.xsd
            XmlReaderSettings settings = new XmlReaderSettings();
            
// wire up handler to get any validation errors
            settings.ValidationEventHandler += settings_ValidationEventHandler;

            
// set the validation type to schema (used to be XsdValidate property in Beta1)
            settings.ValidationType = ValidationType.Schema;

            
// add book.xsd
            settings.Schemas.Add(null, XmlReader.Create(@"..\..\Book.xsd"));
            
// make sure we added
            if (settings.Schemas.Count > 0)
            {
                
// open the bookbad.xml file
                using (XmlReader reader = XmlReader.Create(@"..\..\BookBad.xml", settings))
                {
                    
// replaced validReader with reader for the whole loop
                    while (reader.Read())
                    {
                        
if (reader.NodeType == XmlNodeType.Element)
                        {
                            Console.Write(
"<{0}", reader.Name);
                            
while (reader.MoveToNextAttribute())
                            {
                                Console.Write(
" {0}='{1}'", reader.Name,
                                    reader.Value);
                            }
                            Console.Write(
">");
                        }
                        
else if (reader.NodeType == XmlNodeType.Text)
                        {
                            Console.Write(reader.Value);
                        }
                        
else if (reader.NodeType == XmlNodeType.EndElement)
                        {
                            Console.WriteLine(
"</{0}>", reader.Name);
                        }
                    }
                }
            }
        }

        
private static void settings_ValidationEventHandler(object sender, ValidationEventArgs e) 
        {
            Console.WriteLine(
"Validation Error Message: {0}", e.Message);
            Console.WriteLine(
"Validation Error Severity: {0}", e.Severity);
            
if (e.Exception != null)
            {
                Console.WriteLine(
"Validation Error Line Number: {0}", e.Exception.LineNumber);
                Console.WriteLine(
"Validation Error Line Position: {0}", e.Exception.LinePosition);
                Console.WriteLine(
"Validation Error Source: {0}", e.Exception.Source);
                Console.WriteLine(
"Validation Error Source Schema: {0}", e.Exception.SourceSchemaObject);
                Console.WriteLine(
"Validation Error Source Uri: {0}", e.Exception.SourceUri);
                Console.WriteLine(
"Validation Error thrown from: {0}", e.Exception.TargetSite);
                Console.WriteLine(
"Validation Error callstack: {0}", e.Exception.StackTrace);
            }
        }
        
#endregion
    
        
#region "15.5 Creating an XML Document Programmatically"    
        
public static void CreateXml()
        {
            XmlWriterSettings settings 
= new XmlWriterSettings();
            settings.Indent 
= true;
            
using (XmlWriter writer = XmlWriter.Create(Console.Out, settings))
            {
                writer.WriteStartElement(
"AddressBook");
                writer.WriteStartElement(
"Contact");
                writer.WriteAttributeString(
"name""Tim");
                writer.WriteAttributeString(
"phone""999-888-0000");
                writer.WriteEndElement();
                writer.WriteStartElement(
"Contact");
                writer.WriteAttributeString(
"name""Newman");
                writer.WriteAttributeString(
"phone""666-666-6666");
                writer.WriteEndElement();
                writer.WriteStartElement(
"Contact");
                writer.WriteAttributeString(
"name""Harold");
                writer.WriteAttributeString(
"phone""777-555-3333");
                writer.WriteEndElement();
                writer.WriteEndElement();
            }

            
// Start by making an XmlDocument
            XmlDocument xmlDoc = new XmlDocument();
            
// create a root node for the document
            XmlElement addrBook = xmlDoc.CreateElement("AddressBook");
            xmlDoc.AppendChild(addrBook);
            
// create the Tim contact
            XmlElement contact = xmlDoc.CreateElement("Contact");
            contact.SetAttribute(
"name","Tim");
            contact.SetAttribute(
"phone","999-888-0000");
            addrBook.AppendChild(contact);
            
// create the Newman contact
            contact = xmlDoc.CreateElement("Contact");
            contact.SetAttribute(
"name","Newman");
            contact.SetAttribute(
"phone","666-666-6666");
            addrBook.AppendChild(contact);
            
// create the Harold contact
            contact = xmlDoc.CreateElement("Contact");
            contact.SetAttribute(
"name","Harold");
            contact.SetAttribute(
"phone","777-555-3333");
            addrBook.AppendChild(contact);

            
// Display XML
            Console.WriteLine("Generated XML:\r\n{0}",addrBook.OuterXml);
            Console.WriteLine();
        }
        
#endregion
    
        
#region "15.6 Detecting Changes to an XML Document"    
        
public static void DetectXmlChanges()
        {
            
string xmlFragment = "<?xml version='1.0'?>" +
                
"<!-- My sample XML -->" +
                
"<?pi myProcessingInstruction?>" +
                
"<Root>" + 
                
"<Node1 nodeId='1'>First Node</Node1>" +
                
"<Node2 nodeId='2'>Second Node</Node2>" +
                
"<Node3 nodeId='3'>Third Node</Node3>" +
                
@"<Node4><![CDATA[<>\&']]></Node4>" +
                
"</Root>"

            XmlDocument doc 
= new XmlDocument();
            doc.LoadXml(xmlFragment);

            
//Create the event handlers.
            doc.NodeChanging += new XmlNodeChangedEventHandler(NodeChangingEvent);
            doc.NodeChanged 
+= new XmlNodeChangedEventHandler(NodeChangedEvent);
            doc.NodeInserting 
+= new XmlNodeChangedEventHandler(NodeInsertingEvent);
            doc.NodeInserted 
+= new XmlNodeChangedEventHandler(NodeInsertedEvent);
            doc.NodeRemoving 
+= new XmlNodeChangedEventHandler(NodeRemovingEvent);
            doc.NodeRemoved 
+= new XmlNodeChangedEventHandler(NodeRemovedEvent);

            
// Add a new element node.
            XmlElement elem = doc.CreateElement("Node5");
            XmlText text 
= doc.CreateTextNode("Fifth Element");
            doc.DocumentElement.AppendChild(elem);
            doc.DocumentElement.LastChild.AppendChild(text);

            
// Change the first node
            doc.DocumentElement.FirstChild.InnerText = "1st Node";

            
// remove the fourth node
            XmlNodeList nodes = doc.DocumentElement.ChildNodes;
            
foreach(XmlNode node in nodes)
            {
                
if(node.Name == "Node4")
                {
                    doc.DocumentElement.RemoveChild(node);
                    
break;
                }
            }

            StringBuilder sb 
= new StringBuilder(doc.OuterXml.Length);
            XmlWriterSettings settings 
= new XmlWriterSettings();
            settings.Indent 
= true;
            XmlWriter writer 
= XmlWriter.Create(sb,settings);
            writer.WriteRaw(doc.OuterXml);
            writer.Close();
            Console.WriteLine(sb.ToString());

            
// write out the new xml
            Console.WriteLine(doc.OuterXml);
        }

        
private static void WriteNodeInfo(string action, XmlNode node)
        {
            
if (node.Value != null)
            {
                Console.WriteLine(
"Element: <{0}> {1} with value {2}"
                    node.Name,action,node.Value);
            }
            
else
                Console.WriteLine(
"Element: <{0}> {1} with null value"
                    node.Name,action);
        }

        
public static void NodeChangingEvent(object source, XmlNodeChangedEventArgs e)
        {
            WriteNodeInfo(
"changing",e.Node);
        }

        
public static void NodeChangedEvent(object source, XmlNodeChangedEventArgs e)
        {
            WriteNodeInfo(
"changed",e.Node);
        }

        
public static void NodeInsertingEvent(object source, XmlNodeChangedEventArgs e)
        {
            WriteNodeInfo(
"inserting",e.Node);
        }

        
public static void NodeInsertedEvent(object source, XmlNodeChangedEventArgs e)
        {
            WriteNodeInfo(
"inserted",e.Node);
        }

        
public static void NodeRemovingEvent(object source, XmlNodeChangedEventArgs e)
        {
            WriteNodeInfo(
"removing",e.Node);
        }

        
public static void NodeRemovedEvent(object source, XmlNodeChangedEventArgs e)
        {
            WriteNodeInfo(
"removed",e.Node);
        }
        
        
#endregion
    
        
#region "15.7 Handling Invalid Characters in an XML String"    
        
public static void HandleInvalidChars()
        {
            
// set up a string with our invalid chars
            string invalidChars = @"<>\&'";
            XmlWriterSettings settings 
= new XmlWriterSettings();
            settings.Indent 
= true;
            
using (XmlWriter writer = XmlWriter.Create(Console.Out, settings))
            {
                writer.WriteStartElement(
"Root");
                writer.WriteStartElement(
"InvalidChars1");
                writer.WriteCData(invalidChars);
                writer.WriteEndElement();
                writer.WriteElementString(
"InvalidChars2", invalidChars);
                writer.WriteEndElement();
            }

            
// set up a string with our invalid chars
            invalidChars = @"<>\&'";

            XmlDocument xmlDoc 
= new XmlDocument();
            
// create a root node for the document
            XmlElement root = xmlDoc.CreateElement("Root");
            xmlDoc.AppendChild(root);

            
// create the first invalid character node
            XmlElement invalidElement1 = xmlDoc.CreateElement("InvalidChars1");
            
// wrap the invalid chars in a CDATA section and use the 
            
// InnerXML property to assign the value as it doesn't
            
// escape the values, just passes in the text provided
            invalidElement1.AppendChild(xmlDoc.CreateCDataSection(invalidChars));
            
// append the element to the root node
            root.AppendChild(invalidElement1);

            
// create the second invalid character node
            XmlElement invalidElement2 = xmlDoc.CreateElement("InvalidChars2");
            
// Add the invalid chars directly using the InnerText 
            
// property to assign the value as it will automatically
            
// escape the values
            invalidElement2.InnerText = invalidChars;
            
// append the element to the root node
            root.AppendChild(invalidElement2);

            Console.WriteLine(
"Generated XML with Invalid Chars:\r\n{0}",xmlDoc.OuterXml);
            Console.WriteLine();
        }
        
#endregion
    
        
#region "15.8 Transforming XML"    
        
public static void TransformXml()
        {
            
// Create a resolver with default credentials.
            XmlUrlResolver resolver = new XmlUrlResolver();
            resolver.Credentials 
= System.Net.CredentialCache.DefaultCredentials;

            
// transform the personnel.xml file to html
            XslCompiledTransform transform = new XslCompiledTransform();
            XsltSettings settings 
= new XsltSettings();
            
// disable both of these (the default) for security reasons
            settings.EnableDocumentFunction = false;
            settings.EnableScript 
= false;
            
// load up the stylesheet
            transform.Load(@"..\..\PersonnelHTML.xsl",settings,resolver);
            
// perform the transformation
            transform.Transform(@"..\..\Personnel.xml",@"..\..\Personnel.html");


            
// transform the personnel.xml file to comma delimited format

            
// load up the stylesheet
            transform.Load(@"..\..\PersonnelCSV.xsl",settings,resolver);
            
// perform the transformation
            transform.Transform(@"..\..\Personnel.xml",
                
@"..\..\Personnel.csv");
        }
        
#endregion
    
        
#region "15.9 Tearing Apart an XML Document"    
        
public static void ProcessInvoice()
        {
            XmlDocument xmlDoc 
= new XmlDocument();
            
// pick up invoice from deposited directory
            xmlDoc.Load(@"..\..\Invoice.xml");
            
// get the Invoice element node
            XmlNode Invoice = xmlDoc.SelectSingleNode("/Invoice");

            
// get the invoice date attribute
            XmlAttribute invDate = 
                (XmlAttribute)Invoice.Attributes.GetNamedItem(
"invoiceDate");
            
// get the invoice number attribute
            XmlAttribute invNum = 
                (XmlAttribute)Invoice.Attributes.GetNamedItem(
"invoiceNumber");

            
// Process the billing information to Accounting
            WriteInformation(@"..\..\BillingEnvelope.xml",
                            
"BillingEnvelope",
                            invDate, invNum, xmlDoc,
                            
"/Invoice/billInfo");

            
// Process the shipping information to Accounting
            WriteInformation(@"..\..\ShippingEnvelope.xml",
                            
"ShippingEnvelope",
                            invDate, invNum, xmlDoc,
                            
"/Invoice/shipInfo");

            
// Process the item information to Fulfillment
            WriteInformation(@"..\..\FulfillmentEnvelope.xml",
                            
"FulfillmentEnvelope",
                            invDate, invNum, xmlDoc,
                            
"/Invoice/Items/item");

            
// Now send the data to the web services ?
        }

        
private static void WriteInformation(string path,
                                    
string rootNode,
                                    XmlAttribute invDate,
                                    XmlAttribute invNum,
                                    XmlDocument xmlDoc,
                                    
string nodePath)
        {
            XmlWriterSettings settings 
= new XmlWriterSettings();
            settings.Indent 
= true;
            
using (XmlWriter writer =
                XmlWriter.Create(path, settings))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement(rootNode);
                writer.WriteAttributeString(invDate.Name, invDate.Value);
                writer.WriteAttributeString(invNum.Name, invNum.Value);
                XmlNodeList nodeList 
= xmlDoc.SelectNodes(nodePath);
                
// add the billing information to the envelope
                foreach (XmlNode node in nodeList)
                {
                    writer.WriteRaw(node.OuterXml);
                }
                writer.WriteEndElement();
                writer.WriteEndDocument();
            }
        }

        
#endregion
    
        
#region "15.10 Putting Together an XML Document"    
        
public static void ReceiveInvoice()
        {
            XmlDocument invoice 
= new XmlDocument();
            XmlDocument billing 
= new XmlDocument();
            XmlDocument shipping 
= new XmlDocument();
            XmlDocument fulfillment 
= new XmlDocument();

            
// set up root invoice node
            XmlElement invoiceElement = invoice.CreateElement("Invoice");
            invoice.AppendChild(invoiceElement);
    
            
// load the billing 
            billing.Load(@"..\..\BillingEnvelope.xml");
            
// get the invoice date attribute
            XmlAttribute invDate =        (XmlAttribute)
                billing.DocumentElement.Attributes.GetNamedItem(
"invoiceDate");
            
// get the invoice number attribute
            XmlAttribute invNum = (XmlAttribute)
                billing.DocumentElement.Attributes.GetNamedItem(
"invoiceNumber");
            
// set up the invoice with this info
            invoice.DocumentElement.Attributes.SetNamedItem(invDate.Clone());
            invoice.DocumentElement.Attributes.SetNamedItem(invNum.Clone());
            
// add the billInfo back in
            XmlNodeList billList = billing.SelectNodes("/BillingEnvelope/billInfo");
            
foreach(XmlNode billInfo in billList)
            {
                invoice.DocumentElement.AppendChild(invoice.ImportNode(billInfo,
true));
            }

            
// load the shipping 
            shipping.Load(@"..\..\ShippingEnvelope.xml");
            
// add the shipInfo back in
            XmlNodeList shipList = shipping.SelectNodes("/ShippingEnvelope/shipInfo");
            
foreach(XmlNode shipInfo in shipList)
            {
                invoice.DocumentElement.AppendChild(invoice.ImportNode(shipInfo,
true));
            }

            
// load the items
            fulfillment.Load(@"..\..\FulfillmentEnvelope.xml");
    
            
// Create an Items element in the Invoice to add these under
            XmlElement items = invoice.CreateElement("Items");

            
// add the items back in under Items
            XmlNodeList itemList = fulfillment.SelectNodes("/FulfillmentEnvelope/item");
            
foreach(XmlNode item in itemList)
            {
                items.AppendChild(invoice.ImportNode(item,
true));
            }

            
// add it in
            invoice.DocumentElement.AppendChild(items.Clone());

            
// display Invoice XML
            Console.WriteLine("Invoice:\r\n{0}",invoice.OuterXml);

            
// save our reconstitued invoice
            invoice.Save(@"..\..\ReceivedInvoice.xml");
        }
        
#endregion

        
#region "15.11 Re-Validate modified XML documents without reloading"
        
// set the initial check for validity to true
        static bool bValidXml = true;
        
public static void TestContinualValidation()
        {
            
string xmlFile = @"..\..\Book.xml";
            
string xsdFile = @"..\..\Book.xsd";

            
// Create the schema set
            XmlSchemaSet schemaSet = new XmlSchemaSet();
            
// add the new schema with the target namespace
            
// (could add all the schema at once here if there are multiple)
            schemaSet.Add("http://tempuri.org/Book.xsd", XmlReader.Create(xsdFile));

            
// load up the xml file
            XmlDocument xmlDoc = new XmlDocument();
            
// add the schema
            xmlDoc.Schemas = schemaSet;
            
// validate after load
            xmlDoc.Load(xmlFile);
            ValidationEventHandler eventHandler 
= ValidationEventHandler_15_11;
            xmlDoc.Validate(eventHandler);

            
// add in a new node that is not in the schema
            
// since we have already validated, no callbacks fire during the add
            XmlNode newNode = xmlDoc.CreateElement("BogusElement");
            newNode.InnerText 
= "Totally";
            
// add the new element
            xmlDoc.DocumentElement.AppendChild(newNode);
            
// now we will do validation of the new stuff we added
            xmlDoc.Validate(eventHandler);

            
if (bValidXml == true)
            {
                Console.WriteLine(
"Successfully validated modified XML");
            }
            
else
            {
                Console.WriteLine(
"Modified XML did not validate successfully");
            }
        }

        
private static void ValidationEventHandler_15_11(object sender, ValidationEventArgs e)
        {
            
// we got called so this isn't valid
            bValidXml = false;
            Console.WriteLine(
"Validation Error Message: {0}", e.Message);
            Console.WriteLine(
"Validation Error Severity: {0}", e.Severity);
            
if (e.Exception != null)
            {
                Console.WriteLine(
"Validation Error Line Number: {0}", e.Exception.LineNumber);
                Console.WriteLine(
"Validation Error Line Position: {0}", e.Exception.LinePosition);
                Console.WriteLine(
"Validation Error Source: {0}", e.Exception.Source);
                Console.WriteLine(
"Validation Error Source Schema: {0}", e.Exception.SourceSchemaObject);
                Console.WriteLine(
"Validation Error Source Uri: {0}", e.Exception.SourceUri);
                Console.WriteLine(
"Validation Error thrown from: {0}", e.Exception.TargetSite);
                Console.WriteLine(
"Validation Error callstack: {0}", e.Exception.StackTrace);
            }
        }
        
#endregion
                
        
#region "15.12 Extending transformations"
        
public static void TestExtendingTransformations()
        {
            
string xmlFile = @"..\..\publications.xml";
            
string xslt = @"..\..\publications.xsl";

            
//Create the XslCompiledTransform and load the style sheet.
            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load(xslt);
            
// load the xml
            XPathDocument xPathDoc = new XPathDocument(xmlFile);

            
// make up the args for the stylesheet with the extension object
            XsltArgumentList xslArg = new XsltArgumentList();
            XslExtensionObject xslExt 
= new XslExtensionObject();
            xslArg.AddExtensionObject(
"urn:xslext", xslExt);

            
// send output to the console and do the transformation
            using (XmlWriter writer = XmlWriter.Create(Console.Out))
            {
                transform.Transform(xPathDoc, xslArg, writer);
            }
        }

        
// Our extension object to help with functionality
        public class XslExtensionObject
        {
            
public XPathNodeIterator GetErrata(XPathNodeIterator nodeChapter)
            {
                
try
                {
                    
// In here we could go do other lookup calls (XML, database, web service) to get information to
                    
// add back in to the transformation result
                    string errata = string.Format("<Errata>{0} has {1} errata</Errata>", nodeChapter.Current.Value, nodeChapter.Current.Value.Length);
                    XmlDocument xDoc 
= new XmlDocument();
                    xDoc.LoadXml(errata);
                    XPathNavigator xPathNav 
= xDoc.CreateNavigator();
                    xPathNav.MoveToChild(XPathNodeType.Element);
                    XPathNodeIterator iter 
= xPathNav.Select(".");
                    
return iter;
                }
                
catch (Exception e)
                {
                    
// eat the exception as we were unable to use the extension
                    
// so just return the original iterator
                    Debug.WriteLine(e.ToString());
                    
return nodeChapter;
                }
            }
        }

        
#endregion

        
#region "15.13 Get your schema in bulk from existing XML files"
        
public static void TestBulkSchema()
        {
            DirectoryInfo di 
= new DirectoryInfo(@"..\..");
            
string dir = di.FullName;
            GenerateSchemaForDirectory(dir);
        }

        
public static void GenerateSchemaForDirectory(string dir)
        {
            
// make sure the directory exists
            if (Directory.Exists(dir))
            {
                
// get the files in the directory
                string[] files = Directory.GetFiles(dir, "*.xml");
                
foreach (string file in files)
                {
                    
// set up a reader for the file
                    using (XmlReader reader = XmlReader.Create(file))
                    {
                        XmlSchemaSet schemaSet 
= new XmlSchemaSet();
                        XmlSchemaInference schemaInference 
=
                                        
new XmlSchemaInference();

                        
// get the schema
                        schemaSet = schemaInference.InferSchema(reader);

                        
string schemaPath = "";
                        
foreach (XmlSchema schema in schemaSet.Schemas())
                        {
                            
// make schema file path
                            schemaPath = Path.GetDirectoryName(file) + @"\" +
                                            Path.GetFileNameWithoutExtension(file) 
+ ".xsd";
                            
using (FileStream fs =
                                
new FileStream(schemaPath, FileMode.OpenOrCreate))
                            {
                                schema.Write(fs);
                            }
                        }
                    }
                }
            }
        }
        
#endregion

        
#region "15.14 Passing parameters to transforms"
        
public static void TestXSLTParams()
        {
            XsltArgumentList args 
= new XsltArgumentList();
            args.AddParam(
"storeTitle""""Hero Comics Inventory");
            args.AddParam(
"pageDate""", DateTime.Now.ToString("F"));

            
// Create a resolver with default credentials.
            XmlUrlResolver resolver = new XmlUrlResolver();
            resolver.Credentials 
= System.Net.CredentialCache.DefaultCredentials;

            XslCompiledTransform transform 
= new XslCompiledTransform();
            
// load up the stylesheet
            transform.Load(@"..\..\ParameterExample.xslt", XsltSettings.Default, resolver);
            
// perform the transformation
            FileStream fs = null;
            
using (fs =
                
new FileStream(@"..\..\ParameterExample.htm",
                                FileMode.OpenOrCreate, FileAccess.Write))
            {
                transform.Transform(
@"..\..\ParameterExample.xml", args, fs);
            }

            
// now change the parameters and reprocess
            args = new XsltArgumentList();
            args.AddParam(
"storeTitle""""Fabulous Adventures Inventory");
            args.AddParam(
"pageDate""", DateTime.Now.ToString("D"));
            
using (fs = new FileStream(@"..\..\ParameterExample2.htm",
                FileMode.OpenOrCreate, FileAccess.Write))
            {
                transform.Transform(
@"..\..\ParameterExample.xml", args, fs);
            }
        }
        
#endregion
        

    }
}

转载于:https://www.cnblogs.com/jiangguanghe/archive/2008/11/03/1325700.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值