Tải bản đầy đủ - 0 (trang)
6-1. Show the Structure of an XML Document in a TreeView

6-1. Show the Structure of an XML Document in a TreeView

Tải bản đầy đủ - 0trang

CHAPTER 6 ■ XML PROCESSING



Solution

Load the XML document using the System.Xml.XmlDocument class. Create a reentrant method that

converts a single XmlNode into a System.Windows.Forms.TreeNode, and call it recursively to walk through

the entire document.



How It Works

The .NET Framework provides several different ways to process XML documents. The one you use

depends in part upon your programming task. One of the most fully featured classes is XmlDocument,

which provides an in-memory representation of an XML document that conforms to the W3C Document

Object Model (DOM). The XmlDocument class allows you to browse through the nodes in any direction,

insert and remove nodes, and change the structure on the fly. For details of the DOM specification, go to

www.w3c.org.



■ Note The XmlDocument class is not scalable for very large XML documents, because it holds the entire XML

content in memory at once. If you want a more memory-efficient alternative, and you can afford to read and

process the XML piece by piece, consider the XmlReader and XmlWriter classes described in recipe 6-7.



To use the XmlDocument class, simply create a new instance of the class and call the Load method with

a file name, a Stream, a TextReader, or an XmlReader object. It is also possible to read the XML from a

simple string with the LoadXML method. You can even supply a string with a URL that points to an XML

document on the Web using the Load method. The XmlDocument instance will be populated with the tree

of elements, or nodes, from the source document. The entry point for accessing these nodes is the root

element, which is provided through the XmlDocument.DocumentElement property. DocumentElement is an

XmlElement object that can contain one or more nested XmlNode objects, which in turn can contain more

XmlNode objects, and so on. An XmlNode is the basic ingredient of an XML file. Common XML nodes

include elements, attributes, comments, and contained text.

When dealing with an XmlNode or a class that derives from it (such as XmlElement or XmlAttribute),

you can use the following basic properties:





ChildNodes is an XmlNodeList collection that contains the first level of nested

nodes.







Name is the name of the node.







NodeType returns a member of the System.Xml.XmlNodeType enumeration that

indicates the type of the node (element, attribute, text, and so on).







Value is the content of the node, if it’s a text or CDATA node.







Attributes provides a collection of node objects representing the attributes

applied to the element.







InnerText retrieves a string with the concatenated value of the node and all nested

nodes.



262



www.it-ebooks.info



CHAPTER 6 ■ XML PROCESSING







InnerXml retrieves a string with the concatenated XML markup for all nested

nodes.







OuterXml retrieves a string with the concatenated XML markup for the current

node and all nested nodes.



The Code

The following example walks through every element of an XmlDocument using the ChildNodes property

and a recursive method. Each node is displayed in a TreeView control, with descriptive text that either

identifies it or shows its content.

using

using

using

using



System;

System.Windows.Forms;

System.Xml;

System.IO;



namespace Apress.VisualCSharpRecipes.Chapter06

{

public partial class Recipe06_01 : System.Windows.Forms.Form

{

public Recipe06_01()

{

InitializeComponent();

}

// Default the file name to the sample document.

private void Recipe06_01_Load(object sender, EventArgs e)

{

txtXmlFile.Text = Path.Combine(Application.StartupPath,

@"..\..\ProductCatalog.xml");

}

private void cmdLoad_Click(object sender, System.EventArgs e)

{

// Clear the tree.

treeXml.Nodes.Clear();

// Load the XML document.

XmlDocument doc = new XmlDocument();

try

{

doc.Load(txtXmlFile.Text);

}

catch (Exception err)

{

MessageBox.Show(err.Message);

return;

}



263



www.it-ebooks.info



CHAPTER 6 ■ XML PROCESSING



// Populate the TreeView.

ConvertXmlNodeToTreeNode(doc, treeXml.Nodes);

// Expand all nodes.

treeXml.Nodes[0].ExpandAll();

}

private void ConvertXmlNodeToTreeNode(XmlNode xmlNode,

TreeNodeCollection treeNodes)

{

// Add a TreeNode node that represents this XmlNode.

TreeNode newTreeNode = treeNodes.Add(xmlNode.Name);

// Customize the TreeNode text based on the XmlNode

// type and content.

switch (xmlNode.NodeType)

{

case XmlNodeType.ProcessingInstruction:

case XmlNodeType.XmlDeclaration:

newTreeNode.Text = "
xmlNode.Value + "?>";

break;

case XmlNodeType.Element:

newTreeNode.Text = "<" + xmlNode.Name + ">";

break;

case XmlNodeType.Attribute:

newTreeNode.Text = "ATTRIBUTE: " + xmlNode.Name;

break;

case XmlNodeType.Text:

case XmlNodeType.CDATA:

newTreeNode.Text = xmlNode.Value;

break;

case XmlNodeType.Comment:

newTreeNode.Text = "";

break;

}

// Call this routine recursively for each attribute.

// (XmlAttribute is a subclass of XmlNode.)

if (xmlNode.Attributes != null)

{

foreach (XmlAttribute attribute in xmlNode.Attributes)

{

ConvertXmlNodeToTreeNode(attribute, newTreeNode.Nodes);

}

}



264



www.it-ebooks.info



CHAPTER 6 ■ XML PROCESSING



// Call this routine recursively for each child node.

// Typically, this child node represents a nested element

// or element content.

foreach (XmlNode childNode in xmlNode.ChildNodes)

{

ConvertXmlNodeToTreeNode(childNode, newTreeNode.Nodes);

}

}

}

}



Usage

As an example, consider the following simple XML file (which is included with the sample code as the

ProductCatalog.xml file):







Freeman and Freeman Unique Catalog 2010

2012-01-01





Gourmet Coffee

Beans from rare Chillean plantations.

0.99

true





Blue China Tea Pot

A trendy update for tea drinkers.

102.99

true







Figure 6-1 shows how this file will be rendered in the Recipe06_01 form.



265



www.it-ebooks.info



CHAPTER 6 ■ XML PROCESSING



Figure 6-1. The displayed structure of an XML document



6-2. Insert Nodes in an XML Document

Problem

You need to modify an XML document by inserting new data, or you want to create an entirely new XML

document in memory.



Solution

Create the node using the appropriate XmlDocument method (such as CreateElement, CreateAttribute,

CreateNode, and so on). Then insert it using the appropriate XmlNode method (such as InsertAfter,

InsertBefore, or AppendChild).



How It Works

Inserting a node into the XmlDocument class is a two-step process. You must first create the node, and

then you insert it at the appropriate location. You can then call XmlDocument.Save to persist changes.



266



www.it-ebooks.info



CHAPTER 6 ■ XML PROCESSING



To create a node, you use one of the XmlDocument methods starting with the word Create, depending

on the type of node. This ensures that the node will have the same namespace as the rest of the

document. (Alternatively, you can supply a namespace as an additional string argument.) Next, you

must find a suitable related node and use one of its insertion methods to add the new node to the tree.



The Code

The following example demonstrates this technique by programmatically creating a new XML

document:

using System;

using System.Xml;

namespace Apress.VisualCSharpRecipes.Chapter06

{

public class Recipe06_02

{

private static void Main()

{

// Create a new, empty document.

XmlDocument doc = new XmlDocument();

XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

doc.AppendChild(docNode);

// Create and insert a new element.

XmlNode productsNode = doc.CreateElement("products");

doc.AppendChild(productsNode);

// Create a nested element (with an attribute).

XmlNode productNode = doc.CreateElement("product");

XmlAttribute productAttribute = doc.CreateAttribute("id");

productAttribute.Value = "1001";

productNode.Attributes.Append(productAttribute);

productsNode.AppendChild(productNode);

// Create and add the subelements for this product node

// (with contained text data).

XmlNode nameNode = doc.CreateElement("productName");

nameNode.AppendChild(doc.CreateTextNode("Gourmet Coffee"));

productNode.AppendChild(nameNode);

XmlNode priceNode = doc.CreateElement("productPrice");

priceNode.AppendChild(doc.CreateTextNode("0.99"));

productNode.AppendChild(priceNode);

// Create and add another product node.

productNode = doc.CreateElement("product");

productAttribute = doc.CreateAttribute("id");

productAttribute.Value = "1002";

productNode.Attributes.Append(productAttribute);

productsNode.AppendChild(productNode);



267



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

6-1. Show the Structure of an XML Document in a TreeView

Tải bản đầy đủ ngay(0 tr)

×