using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Xml.Linq;
using System.Xml;
namespace ConsoleTest
{
    
class SchemaTest
    
{
        
static void Main(string[] args)
        
{
            Console.ForegroundColor 
= ConsoleColor.Green;
            XDocument books 
= new XDocument(
                                
new XDeclaration("1.0""utf-8""yes"),
                                
new XElement("books",
                                
new XElement("book"new XAttribute("publishdate""2008"),
                                
new XElement("bookname"" LINQ TO XML  "),
                                
new XElement("author""Fabrice Marguerie"),
                                
new XElement("price""29$")),
                                
new XElement("book"new XAttribute("publishdate""2003"),
                                
new XElement("bookname"" Professional LINQ  "),
                                
new XElement("author"" Scott Klein"),
                                
new XElement("price""19$"))));


            Console.WriteLine(books);
            Console.WriteLine(
"----------------------------------------------");
            ShowXmlElement(books);
            Console.ReadLine();
        }


        
public static void ShowXmlElement(XDocument xNode) 
        
{
            var q 
= from t in xNode.Elements("books").Elements("book") select t;
            
foreach (var node in q) 
            
{
                Console.Write(
"书籍名称:{0}",node.Element("bookname").Value);
                ShowAttribute(node);
                Console.WriteLine(
"作者名称:{0}", node.Element("author").Value);
                Console.WriteLine(
"价格:{0}", node.Element("price").Value);
                Console.WriteLine();
            }

            Console.WriteLine(
"ok");
        }

      

        
public static void ShowAttribute(XElement xNode)
        
{
            
if (xNode.HasAttributes)
            
{
                
foreach (var objAtt in xNode.Attributes())
                
{
                    Console.WriteLine(
"     出版日期:{0}", objAtt.Value);
                }

            }

        }


    }

}



通过以上代码测试了,XML文档的建立、查询及XML文档中属性的判断
输出结果
posted on 2008-05-07 13:34  forrestsun  阅读(225)  评论(0编辑  收藏  举报