>  기사  >  백엔드 개발  >  LINQ to XML 프로그래밍을 기반으로 한 그래픽 코드에 대한 자세한 소개

LINQ to XML 프로그래밍을 기반으로 한 그래픽 코드에 대한 자세한 소개

黄舟
黄舟원래의
2017-03-07 16:55:371456검색

1. LINQ to XML 클래스

LINQ to XML 프로그래밍을 기반으로 한 그래픽 코드에 대한 자세한 소개

다음 코드는 LINQ 사용 방법을 보여줍니다. XML로 빠르게 생성하려면


줄 번호 숨기기 코드 복사 ? XML 생성

public static void CreateDocument()
{
    string path = @"d:\website";

    XDocument xdoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"),
                                   new XElement("Root", "root"));

    xdoc.Save(path);
}

이 예제를 실행하면 내용이 다음과 같은 XML 파일이 생성됩니다.

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

2. XElement 클래스

XElement 클래스는 LINQ 중 하나입니다. 기본 클래스를 XML로 변환합니다. 이는 XML 요소를 나타냅니다. 이 클래스를 사용하여 요소의 콘텐츠를 변경하거나, 요소에 속성을 추가, 변경하거나, 텍스트 형식으로 요소의 콘텐츠를 직렬화할 수 있습니다. 또한 XmlReader, XmlWriter 및 XslCompiledTransform과 같은 System.Xml의 다른 클래스와 상호 운용됩니다.

LINQ to XML을 사용하여 XML 문서를 만드는 방법은 여러 가지가 있습니다. 사용할 구체적인 방법은 실제 요구 사항에 따라 다릅니다. XML 문서를 만드는 가장 간단하고 일반적인 방법은 XElement 클래스를 사용하는 것입니다. 다음 코드는 다음을 사용하여 XML 문서를 생성하는 방법을 보여줍니다.

프로그램 코드의 일부입니다.

public static void CreateCategories()
{
    string path = @"d:\website";

    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>
XElement 클래스에는 xml 처리를 쉽게 만드는 여러 메서드가 포함되어 있습니다. 이러한 방법은 MSDN을 참조하세요.

그 중에서 Save, CreateReader, ToString 및 WriteTo 메서드는 더 일반적으로 사용되는 세 가지 메서드입니다.


3. class

XAttribute 클래스는 요소의 속성을 처리하는 데 사용됩니다. 속성은 요소와 연결된 "이름-값" 쌍입니다. 각 요소는 반복되는 이름을 가진 속성을 가질 수 없습니다. XAttribute 클래스를 사용하는 것은 XElement 클래스를 사용하는 것과 매우 유사합니다. 다음 예제에서는 XML 트리를 생성할 때 속성을 추가하는 방법을 보여줍니다.

LINQ to 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.0" encoding="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>
XAttribute 클래스에는 일반적으로 사용되는 세 가지 메서드가 있습니다.

다음 예에서는 제거를 사용하여 첫 번째 요소의 CategoryID 특성을 제거합니다.

줄 번호 표시

LINQ to XML 프로그래밍을 기반으로 한 그래픽 코드에 대한 자세한 소개코드 복사

?

프로그램 코드의 일부입니다.

public static void RemoveAttribute()
{

    XElement xdoc = CreateCategoriesByXAttribute();

    XAttribute xattr = xdoc.Element("Category").Attribute("CategoryID");

    xattr.Remove();

    xdoc.Save(path);

}
이 예제를 실행하면 다음 내용이 포함된 xml 파일이 생성됩니다.
<?xml version="1.0" encoding="utf-8"?>
<Categories>
  <Category>
    <CategoryName>Beverages</CategoryName>
  </Category>
  <Category CategoryID="5c311c1e-ede5-41e5-93f7-5d8b1d7a0346">
    <CategoryName>Condiments</CategoryName>
  </Category>
  <Category CategoryID="bfde8db5-df84-4415-b297-cd04d8db9712">
    <CategoryName>Confections</CategoryName>
  </Category>
</Categories>
실험적으로 다음과 같은 속성 제거 방법을 시도해 보세요.
public static void RemoveAttributeByDoc()
{

    XElement xdoc = CreateCategoriesByXAttribute();

    XAttribute xattr = xdoc.Attribute("CategoryID");

    xattr.Remove();

    xdoc.Save(path);

}
이 예제를 실행하면 카테고리 요소에 CategoryID라는 속성이 없기 때문에 Null 참조 예외가 발생합니다.

4. XDocument 클래스


XDocument 클래스는 선언, 주석, 처리 지침을 포함하여 xml 문서를 처리하는 메서드를 제공합니다. XDocument 객체는 다음을 포함할 수 있습니다.

다음 예제에서는 여러 요소와 속성은 물론 처리 지침과 일부 주석을 포함하는 간단한 xml 문서를 만듭니다.

public static void CreateXDocument()
      {

          XDocument xdoc = new XDocument(

                  new XProcessingInstruction("xml-stylesheet", "title=&#39;EmpInfo&#39;"),

                  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 파일이 생성됩니다. LINQ to XML 프로그래밍을 기반으로 한 그래픽 코드에 대한 자세한 소개

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet title=&#39;EmpInfo&#39;?>
<!--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-->

XDocument 클래스에는 XElement와 동일한 여러 메서드가 포함되어 있습니다. class, 구체적인 내용은 MSDN을 참조하세요. 노드 및 요소 처리를 위한 대부분의 기능은 XElement를 통해 얻을 수 있습니다. 문서 수준 처리 기능이 절대적으로 필요한 경우와 주석, 처리 지침 및 선언에 대한 액세스가 필요한 경우에만 XDocument 클래스를 사용해야 합니다. .

xml 문서를 만든 후 NodesAfterSelf 메서드를 사용하여 지정된 XElement 요소 뒤의 모든 형제 요소를 반환할 수 있습니다. 이 메서드는 하위 요소가 아닌 컬렉션의 형제 요소만 반환한다는 점에 유의해야 합니다. 이 방법은 지연된 실행을 사용합니다. 다음 코드는 이 프로세스를 보여줍니다.


줄 번호 표시

코드 복사

?

프로그램 코드의 일부입니다.

public static void NodesAfterSelf()
{

    XElement root = new XElement("Categories",
        new XElement("Category",
                new XElement("CategoryID", Guid.NewGuid()),
                new XElement("CategoryName", "食品"),
                new XElement("Description", "可以吃的东西")
            )
        );

    foreach (var item in root.Element("Category").Element("CategoryID").NodesAfterSelf())
    {
        Console.WriteLine((item as XElement).Value);
    }
}
2. LINQ to XML 프로그래밍 개념 이 섹션에서는 로드 방법 등 LINQ to XML 프로그래밍과 관련된 개념을 소개합니다. xml, 새로운 xml 생성, xml 정보 조작 및 xml 문서 탐색.

1、加载已有的xml

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

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

public static void LoadFromFile()
{

    XElement root = XElement.Load(path);

    Console.WriteLi


也可以使用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());

    }

2、保存xml

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

3、创建xml

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

4、遍历xml

使用LINQ to XML在xml树中遍历xml是相当简单的。只需要使用XElement和XAttribute类中所提供的方法。Elements和Element方法提供了定位到某个或某些元素的方式。下面的示例演示了如何遍历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);

    }

}

上述代码运行的结果为:

LINQ to XML 프로그래밍을 기반으로 한 그래픽 코드에 대한 자세한 소개 

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

5、操纵xml

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

I.插入

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

LINQ to 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.0" encoding="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.更新

在LINQ to XML中更新xml内容可以使用以下几种方法:

LINQ to XML 프로그래밍을 기반으로 한 그래픽 코드에 대한 자세한 소개

在下面的示例中使用了ReplaceWith与SetElementValue方法对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.0" encoding="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()
  {
      string path = @"d:\";

      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.0" encoding="utf-8"?>

<Categories />

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

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.0" encoding="utf-8"?>

<Categories>

  <Category>

    <CategoryID>1</CategoryID>

    <CategoryName>Beverages</CategoryName>

  </Category>

</Categories>

 

6、处理属性

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.0" encoding="utf-8"?>

<Categories>

  <Category CategoryID="1" AddDate="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

本文总结

本文介绍了LINQ to XML的编程基础,即System.Xml.Linq命名空间中的多个LINQ to XML类,这些类都是LINQ to XML的支持类,它们使得处理xml比使用其他的xml工具容易得多。在本文中,着重介绍的是XElement、XAttribute和XDocument。 

 以上就是LINQ to XML 编程基础的图文代码详细介绍的内容,更多相关内容请关注PHP中文网(www.php.cn)!


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.