Csharp/C Sharp/XML/XmlDocument — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 15:31, 26 мая 2010

A Simple XML Example

 
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
public class MainClass {
    public static void Main() {
        XmlElement xmlBook;
        XmlAttribute xmlParticipantType;
        XmlElement xmlFirstName;
        XmlElement xmlLastName;
        XmlDocument xmlDoc = new XmlDocument();
        XmlElement xmlBooks = xmlDoc.CreateElement("Books");
        xmlDoc.AppendChild(xmlBooks);
        xmlBook = xmlDoc.CreateElement("Book");
        xmlParticipantType = xmlDoc.CreateAttribute("type");
        xmlParticipantType.InnerText = "Author";
        xmlBook.Attributes.Append(xmlParticipantType);
        xmlFirstName = xmlDoc.CreateElement("FirstName");
        xmlFirstName.InnerText = "J";
        xmlBook.AppendChild(xmlFirstName);
        xmlLastName = xmlDoc.CreateElement("LastName");
        xmlLastName.InnerText = "R";
        xmlBook.AppendChild(xmlLastName);
        xmlBooks.AppendChild(xmlBook);
        xmlBook = xmlDoc.CreateElement("Book");
        xmlParticipantType = xmlDoc.CreateAttribute("type");
        xmlParticipantType.InnerText = "Author";
        xmlBook.Attributes.Append(xmlParticipantType);
        xmlFirstName = xmlDoc.CreateElement("FirstName");
        xmlFirstName.InnerText = "E";
        xmlBook.AppendChild(xmlFirstName);
        xmlLastName = xmlDoc.CreateElement("LastName");
        xmlLastName.InnerText = "B";
        xmlBook.AppendChild(xmlLastName);
        xmlBooks.AppendChild(xmlBook);
        XmlNodeList authorsList = xmlDoc.SelectNodes("Books/Book[@type=\"Author\"]");
        foreach (XmlNode node in authorsList) {
            XmlNode firstName = node.SelectSingleNode("FirstName");
            XmlNode lastName = node.SelectSingleNode("LastName");
            Console.WriteLine("{0} {1}", firstName, lastName);
        }
    }
}


Call GetElementsByTagName to get an element

 
using System;
using System.Xml;
public class MainClass {
    private static void Main() {
        XmlDocument doc = new XmlDocument();
        doc.Load("ProductCatalog.xml");
        XmlNodeList prices = doc.GetElementsByTagName("productPrice");
        decimal totalPrice = 0;
        foreach (XmlNode price in prices) {
            totalPrice += Decimal.Parse(price.ChildNodes[0].Value);
        }
        Console.WriteLine("Total catalog value: " + totalPrice.ToString());
    }
}


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 + "\t");
            foreach (XmlAttribute attribute in node.Attributes) {
                Console.Write(attribute.Value + "  ");
            }
        }
    }
}


LoadXml

 
using System;
using System.IO;
using System.Xml;
public class BookListing {
    public static void Main() {
        XmlDocument doc = new XmlDocument();
        String entry = "<book genre="biography"" +
         " ISBN="1111111111"><title>my title</title>" +
         "</book>";
        doc.LoadXml(entry);
        StringWriter writer = new StringWriter();
        doc.Save(writer); // to StringWriter
        String strXML = writer.ToString(); // to String
        Console.WriteLine(strXML);
    }
}


Save, AppendChild, CreateXmlDeclaration, CreateElement

 
using System;
using System.Xml;
class MainClass {
    public static void Main() {
        XmlDocument doc = new XmlDocument();
        XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
        doc.AppendChild(docNode);
        XmlNode productsNode = doc.CreateElement("products");
        doc.AppendChild(productsNode);
        XmlNode productNode = doc.CreateElement("product");
        XmlAttribute productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "1";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);
        XmlNode nameNode = doc.CreateElement("productName");
        nameNode.AppendChild(doc.CreateTextNode("Coffee"));
        productNode.AppendChild(nameNode);
        XmlNode priceNode = doc.CreateElement("productPrice");
        priceNode.AppendChild(doc.CreateTextNode("0.99"));
        productNode.AppendChild(priceNode);
        productNode = doc.CreateElement("product");
        productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "2";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);
        nameNode = doc.CreateElement("productName");
        nameNode.AppendChild(doc.CreateTextNode("Tea Pot"));
        productNode.AppendChild(nameNode);
        priceNode = doc.CreateElement("productPrice");
        priceNode.AppendChild(doc.CreateTextNode("12.99"));
        productNode.AppendChild(priceNode);
        doc.Save(Console.Out);
    }
}


Use Load method in XmlDocument to load xml document

 
//Order.xml
/*
<?xml version="1.0" ?>
<ord:order xmlns:ord="http://mycompany/OrderML"
  xmlns:cli="http://mycompany/ClientML">
    <cli:client>
        <cli:firstName>Sally</cli:firstName>
        <cli:lastName>Sergeyeva</cli:lastName>
    </cli:client>
    <ord:orderItem itemNumber="3211"/>
    <ord:orderItem itemNumber="1155"/>
</ord:order>
*/
using System;
using System.Xml;
class MainClass {
    public 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 + "\t");
            foreach (XmlAttribute attribute in node.Attributes) {
                Console.Write(attribute.Value + "  ");
            }
        }
    }
}


Use SelectNodes to query nodes by XPath

 
using System;
using System.Xml;
class MainClass {
    private static void Main() {
        XmlDocument doc = new XmlDocument();
        doc.Load("orders.xml");
        XmlNodeList nodes = doc.SelectNodes("/Order/Items/Item/Name");
        foreach (XmlNode node in nodes) {
            Console.WriteLine(node.InnerText);
        }
        Console.ReadLine();
    }
}