深圳嘉华_架构师进阶之路_07linq to xml

LINQ to XML

 以下的代码演示了如何使用LINQ to XML来快速创建一个xml

    public static void CreateDocument()
    {
        XDocument xdoc = new XDocument
        (
            new XDeclaration("1.0", "utf-8", "yes"),
            new XElement("Root", "root")
        );
        xdoc.Save(path);
    }

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0encoding="utf-8standalone="yes"?>

<Root>root</Root>

可以看出微软在LINQ上投入了很大的精力,使我们在编程时感觉到很舒服。下面将详细介绍处理XML时使用最多的三个类:XElementXAttributeXDocument。如果掌握了这些类,使用LINQ to XML时将会感到很顺手。

XElement

XElement 类是 LINQ to XML 中的基础类之一。 它表示一个 XML 元素。 可以使用该类创建元素;更改元素内容;添加、更改或删除子元素;向元素中添加属性;或以文本格式序列化元素内容。 还可以与 System.Xml 中的其他类(例如 XmlReaderXmlWriter  XslCompiledTransform)进行互操作。

使用LINQ to XML创建xml文档有很多种方式,具体使用哪种方法要根据实际需要。而创建xml文档最简单、最常见的方式是使用XElement类。以下的代码演示了如何使用XElement类创建一个xml文档:

public static void CreateCategories()
{
    XElement root = new XElement("Categories",
        new XElement("Category",
            new XElement("CategoryID", Guid.NewGuid()),
            new XElement("CategoryName", "Beverages")
            ),
        new XElement("Category",
            new XElement("CategoryID", Guid.NewGuid()),
            new XElement("CategoryName", "Condiments")
            ),
        new XElement("Category",
            new XElement("CategoryID", Guid.NewGuid()),
            new XElement("CategoryName", "Confections")
            )
       );
    root.Save(path);
}

 运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0" encoding="utf-8"?>
<Categories>
  <Category>
    <CategoryID>57485174-46fc-4e8c-8d98-d25b53d504a1</CategoryID>
    <CategoryName>Beverages</CategoryName>
  </Category>
  <Category>
    <CategoryID>1474dde1-8014-48f7-b093-b47ca5d5b770</CategoryID>
    <CategoryName>Condiments</CategoryName>
  </Category>
  <Category>
    <CategoryID>364224e0-e002-4939-90fc-0fd93e0cf35b</CategoryID>
    <CategoryName>Confections</CategoryName>
  </Category>
</Categories>

LINQ to XML的强大之处还在于它可以使用LINQ to SQL或者LINQ to Object获取数据源,然后填充到xml树。以下的示例从Northwind数据库中读取CategoriesProducts表中的数据来创建包含产品类别,以及每个类别下所有产品的xml文件:

public static void CreateCategoriesFromDatabase()
{
    using (NorthwindDataContext db = new NorthwindDataContext())
    {
        XElement root = new XElement("Categories",
                db.Categories
                .Select
                (
                    c => new XElement
                    (
                        "Category"
                        , new XElement("CategoryID", c.CategoryID)
                        , new XElement("CategoryName", c.CategoryName)
                        , new XElement
                            (
                                "Products"
                                , c.Products
                                .Select
                                (
                                    p => new XElement
                                    (
                                        "Product"
                                        , new XElement("ProductName", p.ProductName)
                                    )
                                )
                                .Take(2)
                            )
                    )
                )
                .Take(3)
            );
        root.Save(path);
    }
}

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0encoding="utf-8"?>

<Categories>

  <Category>

    <CategoryID>1</CategoryID>

    <CategoryName>Beverages</CategoryName>

    <Products>

      <Product>

        <ProductName>Chai</ProductName>

      </Product>

      <Product>

        <ProductName>Chang</ProductName>

      </Product>

    </Products>

  </Category>

  <Category>

    <CategoryID>2</CategoryID>

    <CategoryName>Condiments</CategoryName>

    <Products>

      <Product>

        <ProductName>Aniseed Syrup</ProductName>

      </Product>

      <Product>

        <ProductName>Chef Anton's Cajun Seasoning</ProductName>

      </Product>

    </Products>

  </Category>

  <Category>

    <CategoryID>3</CategoryID>

    <CategoryName>Confections</CategoryName>

    <Products>

      <Product>

        <ProductName>Pavlova</ProductName>

      </Product>

      <Product>

        <ProductName>Teatime Chocolate Biscuits</ProductName>

      </Product>

    </Products>

  </Category>

</Categories>

XAttribute

XAttribute类用来处理元素的属性,属性是与元素相关联的“名称-值”对,每个元素中不能有名称重复的属性。使用XAttribute类与使用XElement类的操作十分相似,下面的示例演示了如何在创建xml树时为其添加一个属性:

public static XElement CreateCategoriesByXAttribute()
{
    XElement root = new XElement("Categories",
        new XElement("Category",
            new XAttribute("CategoryID", Guid.NewGuid()),
            new XElement("CategoryName", "Beverages")
            ),
        new XElement("Category",
            new XAttribute("CategoryID", Guid.NewGuid()),
            new XElement("CategoryName", "Condiments")
            ),
        new XElement("Category",
            new XAttribute("CategoryID", Guid.NewGuid()),
            new XElement("CategoryName", "Confections")
            )
       );
    root.Save(path);
    return root;
}

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0encoding="utf-8"?>

<Categories>

  <Category CategoryID="a6d5ef04-3f83-4e00-aeaf-52444add7570">

    <CategoryName>Beverages</CategoryName>

  </Category>

  <Category CategoryID="67a168d5-6b22-4d82-9bd4-67bec88c2ccb">

    <CategoryName>Condiments</CategoryName>

  </Category>

  <Category CategoryID="17398f4e-5ef1-48da-8a72-1c54371b8e76">

    <CategoryName>Confections</CategoryName>

  </Category>

</Categories>

4XDocument

XDocument类提供了处理xml文档的方法,包括声明、注释和处理指令。

下面的示例创建了一个简单的xml文档,它包含几个元素和一个属性,以及一个处理指令和一些注释:

public static void CreateXDocument()
{
    XDocument xdoc = new XDocument(
            new XProcessingInstruction("xml-stylesheet", "title='EmpInfo'"),
            new XComment("some comments"),
            new XElement("Root",
                    new XElement("Employees",
                            new XElement("Employee",
                                    new XAttribute("id", "1"),
                                    new XElement("Name", "Scott Klein"),
                                    new XElement("Title", "Geek"),
                                    new XElement("HireDate","02/05/2007"),
                                    new XElement("Gender", "M")
                                )
                        )
                ),
            new XComment("more comments")
        );
    xdoc.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0encoding="utf-8"?>

<?xml-stylesheet title='EmpInfo'?>

<!--some comments-->

<Root>

  <Employees>

    <Employee id="1">

      <Name>Scott Klein</Name>

      <Title>Geek</Title>

      <HireDate>02/05/2007</HireDate>

      <Gender>M</Gender>

    </Employee>

  </Employees>

</Root>

<!--more comments-->

加载已有的xml

使用LINQ to XML加载xml可以从多种数据源获得,例如字符串、XmlReaderTextReader或文件。

下面的示例演示了如何从文件中加载xml

public static void LoadFromFile()
{
    XElement root = XElement.Load(path);
    Console.WriteLine(root.ToString());
}

也可以使用Parse方法从一个字符串加载xml

public static void LoadFromString()
{
    XElement root = XElement.Parse(@"
        <Categories>
          <Category>
            <CategoryID>1</CategoryID>
            <CategoryName>Beverages</CategoryName>
            <Description>Soft drinks, coffees, teas, beers, and ales</Description>
          </Category>
        </Categories>
    ");
    Console.WriteLine(root.ToString());
}

保存xml

在前面的示例中曾多次调用XElement对象的Save方法来保存xml文档,在这里就不冗述了。

创建xml

在前面的示例中曾多次调用XElement对象的构造函数来创建xml文档,在这里就不冗述了。需要说明的是,在使用LINQ to XML创建xml文档时,会有代码缩进,这使代码的可读性大大加强。

遍历xml

使用LINQ to XMLxml树中遍历xml是相当简单的。只需要使用XElementXAttribute类中所提供的方法。ElementsElement方法提供了定位到某个或某些元素的方式。下面的示例演示了如何遍历xml树,并获取指定元素的方式:

public static void Enum()
{
    XElement root = new XElement("Categories");
    using (NorthwindDataContext db = new NorthwindDataContext())
    {
        root.Add(
                db.Categories
                .Select
                (
                    c => new XElement
                    (
                        "Category"
                        , new XElement("CategoryName", c.CategoryName)
                    )
                )
            );
    }
    foreach (var item in root.Elements("Category"))
    {
        Console.WriteLine(item.Element("CategoryName").Value);
    }
}

上述代码运行的结果为:

是不是很简单呢?Nodes()Elements()Element(name)Elements(name)方法为xml树的导航提供了基本功能。

操纵xml

LINQ to XML一个重要的特性是能够方便地修改xml树,如添加、删除、更新和复制xml文档的内容。

I.插入

使用XNode类的插入方法可以方便地向xml树添加内容:

在下面的示例中,使用AddAfterSelf方法向现有xml中添加一个新节点:

public static void AddAfterSelf()
{
    XElement root = XElement.Parse(@"
        <Categories>
          <Category>
            <CategoryID>1</CategoryID>
            <CategoryName>Beverages</CategoryName>
            <Description>Soft drinks, coffees, teas, beers, and ales</Description>
          </Category>
        </Categories>
    ");
    XElement xele = root.Element("Category").Element("CategoryName");
    xele.AddAfterSelf(new XElement("AddDate", DateTime.Now));
    root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0encoding="utf-8"?>

<Categories>

  <Category>

    <CategoryID>1</CategoryID>

    <CategoryName>Beverages</CategoryName>

    <AddDate>2010-01-31T03:08:51.813736+08:00</AddDate>

    <Description>Soft drinks, coffees, teas, beers, and ales</Description>

  </Category>

</Categories>

当需要添加一个元素到指定节点之前时,可以使用AddBeforeSelf方法。

II.更新

在下面的示例中使用了ReplaceWithSetElementValue方法对xml进行了更新操作:


public static void Update()
{

    XElement root = XElement.Parse(@"
        <Categories>
          <Category>
            <CategoryID>1</CategoryID>
            <CategoryName>Beverages</CategoryName>
            <Description>Soft drinks, coffees, teas, beers, and ales</Description>
          </Category>
        </Categories>
    ");
    root.Element("Category").Element("CategoryID").ReplaceWith(new XElement("ID", "2"));
    root.Element("Category").SetElementValue("CategoryName", "test data");
    root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0encoding="utf-8"?>

<Categories>

  <Category>

    <ID>2</ID>

    <CategoryName>test data</CategoryName>

    <Description>Soft drinks, coffees, teas, beers, and ales</Description>

  </Category>

</Categories>

III.删除

可以使用Remove(XElement)RemoveAll方法来删除xml

在下面的示例中,使用了RemoveAll方法:

public static void Remove()
{
    XElement root = XElement.Parse(@"
        <Categories>
          <Category>
            <CategoryID>1</CategoryID>
            <CategoryName>Beverages</CategoryName>
            <Description>Soft drinks, coffees, teas, beers, and ales</Description>
          </Category>
        </Categories>
    ");
    root.RemoveAll();
    root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0encoding="utf-8"?>

<Categories />

在下面的示例中,使用了Remove方法删除了xmlDescription元素:

public static void Remove()
{
    XElement root = XElement.Parse(@"
        <Categories>
          <Category>
            <CategoryID>1</CategoryID>
            <CategoryName>Beverages</CategoryName>
            <Description>Soft drinks, coffees, teas, beers, and ales</Description>
          </Category>
        </Categories>
    ");
    root.Element("Category").Element("Description").Remove();
    root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0encoding="utf-8"?>

<Categories>

  <Category>

    <CategoryID>1</CategoryID>

    <CategoryName>Beverages</CategoryName>

  </Category>

</Categories>

处理属性

I.添加

LINQ to XML添加属性与添加元素师类似的,可以使用构造函数或者Add方法来添加属性:

public static void AddAttribute()
{
    XElement root = new XElement("Categories",
        new XElement("Category",
            new XAttribute("CategoryID","1"),
            new XElement("CategoryName","Beverages"),
            new XElement("Description", "Soft drinks, coffees, teas, beers, and ales")
        )
    );
    root.Element("Category").Add(new XAttribute("AddDate", DateTime.Now.ToShortDateString()        
    ));
    root.Save(path);
}

运行该示例将会得到一个xml文件,其内容为:

<?xml version="1.0encoding="utf-8"?>

<Categories>

  <Category CategoryID="1AddDate="2010-01-31">

    <CategoryName>Beverages</CategoryName>

    <Description>Soft drinks, coffees, teas, beers, and ales</Description>

  </Category>

</Categories>

II.检索

检索属性可以使用Attribute(name)方法:

public static void SelectAttribute()
{
    XElement root = new XElement("Categories",
        new XElement("Category",
            new XAttribute("CategoryID", "1"),
            new XElement("CategoryName", "Beverages"),
            new XElement("Description", "Soft drinks, coffees, teas, beers, and ales")
        )
    );
    XAttribute xattr = root.Element("Category").Attribute("CategoryID");
    Console.WriteLine(xattr.Name);
    Console.WriteLine(xattr.Value);
}

上述代码的运行结果为:

CategoryID

1

III.删除

删除属性的操作是调用XAttribute对象的Remove方法来完成的。

发布了37 篇原创文章 · 获赞 3 · 访问量 6313

猜你喜欢

转载自blog.csdn.net/huan13479195089/article/details/104831367
今日推荐