Linq to Xml示例

Xml文件:

<?xml version="1.0"?>

<Software xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

  <Databases>

    <Database>

      <Name>Data</Name>

      <Password />

      <InitializeCommand />

      <Tables>

        <Table>

          <Name>DataTable</Name>

          <Columns>

            <Column>

              <Name>ID</Name>

              <Type>Int32</Type>

              <Comment />

            </Column>

            <Column>

              <Name>Name</Name>

              <Type>String</Type>

              <Comment />

            </Column>

            <Column>

              <Name>Meaning</Name>

              <Type>String</Type>

              <Comment />

            </Column>

            <Column>

              <Name>Important</Name>

              <Type>Int32</Type>

              <Comment />

            </Column>

          </Columns>

          <Comment />

        </Table>

      </Tables>

    </Database>

  </Databases>

  <DALNameSpace>WordsHelper.DAL</DALNameSpace>

  <ModelNameSpace>WordsHelper.Model</ModelNameSpace>

  <OutputDirectory>..\Library\</OutputDirectory>

</Software>

查询代码:

var cust = from c in XElement.Load("Last.xml")

                .Elements("Databases").Elements("Database")

                .Elements("Tables").Elements("Table")

                .Elements("Columns").Elements("Column")

            where c.Element("Name").Value == "Name"

            select c;

var x = cust.ToArray()[0].Element("Type").Value;

 简化的代码:

var x = XElement.Load("Last.xml")

    .Elements("Databases")

    .Elements("Database")

    .Elements("Tables")

    .Elements("Table")

    .Elements("Columns")

    .Elements("Column")

    .First(c => c.Element("Name").Value == "Name")

    .Element("Type")

    .Value;

 

你可能感兴趣的:(LINQ)