读取XML并在c#中获取值

时间:2014-04-11 01:37:47

标签: c# xml linq-to-xml

能够使用c#

获取Name,Offset和Length的值的最简洁方法是什么?
<?xml version="1.0" encoding="utf-8" ?>
<RecordLayout>
  <Field>
    <Name>Ali</Name>
    <Offset>1</Offset>
    <Length>2</Length>
  </Field>
  <Field>
    <Name>Bob</Name>
    <Offset>1</Offset>
    <Length>2</Length>
  </Field>
</RecordLayout>

1 个答案:

答案 0 :(得分:1)

使用LINQ to XML可以这样做:

var xmlDocument = XDocument.Load("path");

var elements = xmlDocument
              .Root
              .Elements("Field")
              .Select(x => new
              {
                  Name = (string) x.Element("Name"),
                  Offset = (int) x.Element("Offset"),
                  Length = (int) x.Element("Length")
              });