LINQ系列:LINQ to XML操作

libingql發表於2014-11-02

  LINQ to XML操作XML檔案的方法,如建立XML檔案、新增新的元素到XML檔案中、修改XML檔案中的元素、刪除XML檔案中的元素等。

1. 建立XML檔案

string xmlFilePath = Server.MapPath("Data/Product.xml");

XDocument doc = new XDocument
(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement
    (
        "Products",
        new XElement
        (
            "Product",
            new XAttribute("ID", 1),
            new XElement("ProductName", "LINQ to XML"),
            new XElement("UnitPrice", 10),
            new XElement("Remark", "LINQ to XML操作")
        )
    )
);

// 儲存為XML檔案
doc.Save(xmlFilePath);

// 顯示XML檔案內容
Response.Write(doc);
// 設定網頁顯示的形式為XML檔案
Response.ContentType = "text/xml";
Response.End();
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Products>
  <Product ID="1">
    <ProductName>LINQ to XML</ProductName>
    <UnitPrice>10</UnitPrice>
    <Remark>LINQ to XML操作</Remark>
  </Product>
</Products>
XElement xml = new XElement
(
    "Root",
    new XElement("Product",
        new XAttribute("ID", 1)
    )
);

xml.Save(Environment.CurrentDirectory + @"\" + "Product.xml");
<?xml version="1.0" encoding="utf-8"?>
<Root>
  <Product ID="1" />
</Root>

  根據從資料庫中查詢的資料結構生成一個XML檔案:

using (NorthwindContext context = new NorthwindContext())
{
    var products = from p in context.Products
                    select new
                    {
                        p.ProductID,
                        p.ProductName,
                        p.UnitPrice
                    };

    var xml = new XElement
    (
        "Products",
        from p in products.ToList()
        select new XElement
        (
            "Product",
            new XElement("ProductID", p.ProductID),
            new XElement("ProductName", p.ProductName),
            new XElement("UnitPrice", p.UnitPrice)
        )
    );

    xml.Save(Environment.CurrentDirectory + @"\" + "Products.xml");
}

2. 載入XML檔案

XDocument doc = XDocument.Load(Environment.CurrentDirectory + @"\Product.xml");

foreach (XNode node in doc.Nodes())
{
    Console.WriteLine(node.ToString());
}

  執行輸出:

<!--Created by LINQ to XML-->
<Products>
  <Product>
    <ProductID>1</ProductID>
    <ProductName>LINQ to XML</ProductName>
    <UnitPrice>10</UnitPrice>
  </Product>
  <Product>
    <ProductID>2</ProductID>
    <ProductName>LINQ to SQL</ProductName>
    <UnitPrice>20</UnitPrice>
  </Product>
</Products>
XDocument doc = XDocument.Load(Environment.CurrentDirectory + @"\Product.xml");

foreach (XNode node in doc.Nodes().OfType<XElement>())
{
    Console.WriteLine(node.ToString());
}
<Products>
  <Product>
    <ProductID>1</ProductID>
    <ProductName>LINQ to XML</ProductName>
    <UnitPrice>10</UnitPrice>
  </Product>
  <Product>
    <ProductID>2</ProductID>
    <ProductName>LINQ to SQL</ProductName>
    <UnitPrice>20</UnitPrice>
  </Product>
</Products>
XDocument doc = XDocument.Load(Environment.CurrentDirectory + @"\Product.xml");

foreach (XElement element in doc.Elements())
{
    Console.WriteLine(element.ToString());
}
XElement el = XElement.Load(Environment.CurrentDirectory + @"\Product.xml");

foreach (XElement e in el.Elements("Product"))
{
    Console.WriteLine(e.Element("ProductName").Value);
}
XDocument doc = XDocument.Load(Environment.CurrentDirectory + @"\" + "Product.xml");

var query = from p in doc.Descendants("Product")
            where p.Attribute("ID").Value == "1"
            select p;

foreach (var item in query)
{
    Console.WriteLine(item.Element("ProductName").Value);
}
XDocument doc = XDocument.Load(Environment.CurrentDirectory + @"\" + "Product.xml");

var query = from p in doc.Root.Elements("Product")
            select new
            {
                ProductID = p.Element("ProductID").Value,
                ProductName = p.Element("ProductName").Value,
                UnitPrice = p.Element("UnitPrice").Value
            };
foreach (var item in query)
{
    Console.WriteLine("{0}-{1}-{2}", item.ProductID, item.ProductName, item.UnitPrice);
}

3. 新增元素到XML檔案

XElement el = XElement.Load(Server.MapPath("Data/Product.xml"));

XElement product = new XElement
(
    "Product",
    new XAttribute("ID", 2),
    new XElement("ProductName", "LINQ to Object"),
    new XElement("UnitPrice", 20m),
    new XElement("Remark", "")
);

el.Add(product);
el.Save(Server.MapPath("Data/Product.xml"));
<?xml version="1.0" encoding="utf-8"?>
<Products>
  <Product ID="1">
    <ProductName>LINQ to XML</ProductName>
    <UnitPrice>10</UnitPrice>
    <Remark>LINQ to XML操作</Remark>
  </Product>
  <Product ID="2">
    <ProductName>LINQ to Object</ProductName>
    <UnitPrice>20</UnitPrice>
    <Remark></Remark>
  </Product>
</Products>

4. 修改XML檔案中元素

XElement el = XElement.Load(Server.MapPath("Data/Product.xml"));

IEnumerable<XElement> products = from e in el.Elements("Product")
                                    where e.Attribute("ID").Value == "1"
                                    select e;
if (products.Count() > 0)
{
    XElement product = products.First();
    product.SetAttributeValue("ID", 3);
    product.ReplaceNodes
    (
        new XElement("ProductName", "LINQ to XML Version 2"),
        new XElement("UnitPrice", 30)
    );
}

el.Save(Server.MapPath("Data/Product.xml"));
<?xml version="1.0" encoding="utf-8"?>
<Products>
  <Product ID="3">
    <ProductName>LINQ to XML Version 2</ProductName>
    <UnitPrice>30</UnitPrice>
  </Product>
  <Product ID="2">
    <ProductName>LINQ to Object</ProductName>
    <UnitPrice>20</UnitPrice>
    <Remark></Remark>
  </Product>
</Products>

5. 刪除XML檔案中的元素

XElement el = XElement.Load(Server.MapPath("Data/Product.xml"));

IEnumerable<XElement> products = from e in el.Elements("Product")
                                    where e.Attribute("ID").Value == "2"
                                    select e;
if (products.Count() > 0)
{
    products.First().Remove();
}

el.Save(Server.MapPath("Data/Product.xml"));
XElement xml = XElement.Load(Environment.CurrentDirectory + @"\" + "Product.xml");
xml.Element("Product").Remove(); // 刪除第一個Product子元素
xml.Elements("Product").Remove(); // 刪除全部Product子元素

xml.Save(Environment.CurrentDirectory + @"\" + "Product.xml");
xml.SetElementValue("Product", null); // 刪除第一個Product子元素
XElement xml = XElement.Load(Environment.CurrentDirectory + @"\" + "Product.xml");
xml.Element("Product").SetElementValue("ProductID", 1); // 修改ProductID子元素
xml.Element("Product").SetElementValue("ProductID", null); // 刪除ProductID子元素

6. 將XML檔案中屬性轉換為元素

XElement el = XElement.Load(Server.MapPath("Data/Product.xml"));

IEnumerable<XElement> products = from e in el.Elements("Product")
                                    where e.Attribute("ID").Value == "1"
                                    select e;
if (products.Count() > 0)
{
    XAttribute attr = products.First().FirstAttribute;
    products.First().AddFirst
    (
        new XElement(attr.Name, attr.Value)
    );
    attr.Remove();
}

el.Save(Server.MapPath("Data/Product.xml"));
<?xml version="1.0" encoding="utf-8"?>
<Products>
  <Product>
    <ID>1</ID>
    <ProductName>LINQ to XML</ProductName>
    <UnitPrice>30</UnitPrice>
  </Product>
</Products>

7.XML節點屬性

  1> 新增屬性

XElement xml = XElement.Load(Environment.CurrentDirectory + @"\" + "Product.xml");

XElement product=(from p in xml.Elements("Product")
                    select p).First();
product.Add(new XAttribute("ID", 1));

xml.Save(Environment.CurrentDirectory + @"\" + "Product.xml");

  2> 修改屬性

XElement xml = XElement.Load(Environment.CurrentDirectory + @"\" + "Product.xml");

XElement product = (from p in xml.Elements("Product")
                    select p).First();
product.SetAttributeValue("ID", 2);

xml.Save(Environment.CurrentDirectory + @"\" + "Product.xml");

  3> 刪除屬性

XElement xml = XElement.Load(Environment.CurrentDirectory + @"\" + "Product.xml");

XElement product = (from p in xml.Elements("Product")
                    select p).First();
product.Attribute("ID").Remove();

xml.Save(Environment.CurrentDirectory + @"\" + "Product.xml");

相關文章