使用XDocument解析XML

时间:2011-10-17 19:58:27

标签: c# xml linq-to-xml

我可以使用XDocument从以下xml解析“my_cool_id”吗?

<?xml version="1.0" encoding="UTF-8"?>
<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">
  <fields>
    <field name="field_name_1">
      <value>12345</value>
    </field>
    <field name="my_cool_id">
      <value>12345</value>
    </field>
    <field name="field_name_2">
      <value>12345</value>
    </field>
    <field name="field_name_3">
      <value>12345</value>
    </field>
  </fields>
</xfdf>

1 个答案:

答案 0 :(得分:35)

我怀疑你被名字空间困住了。试试这个:

XDocument doc = XDocument.Load("test.xml");
XNamespace ns = "http://ns.adobe.com/xfdf/";

foreach (XElement element in doc.Root
                                .Element(ns + "fields")
                                .Elements(ns + "field"))
{
    Console.WriteLine("Name: {0}; Value: {1}",
                      (string) element.Attribute("name"),
                      (string) element.Element(ns + "value"));
}

或者只找到一个特定元素:

XDocument doc = XDocument.Load("test.xml");
XNamespace ns = "http://ns.adobe.com/xfdf/";
var field = doc.Descendants(ns + "field")
               .Where(x => (string) x.Attribute("name") == "my_cool_id")
               .FirstOrDefault();

if (field != null)
{
    string value = (string) field.Element("value");
    // Use value here
}