本文介绍了使用解析XML的XDocument的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我能得到一些帮助,使用的XDocument以下XML解析my_cool_id?
<?XML版本=1.0编码=UTF-8&GT?;
< XFDF的xmlns =http://ns.adobe.com/xfdf/XML:空间=preserve>
<&领域GT;
<字段名=field_name_1>
< VALUE> 12345< /值>
< /场>
<字段名=my_cool_id>
< VALUE> 12345< /值>
< /场>
<字段名=field_name_2>
< VALUE> 12345< /值>
< /场>
<字段名=field_name_3>
< VALUE> 12345< /值>
< /场>
< /田>
< / XFDF>
解决方案
我怀疑你被命名空间难住了。试试这个:
的XDocument DOC = XDocument.Load(的test.xml);
NS的XNamespace =http://ns.adobe.com/xfdf/;在doc.Root的foreach(的XElement元素
.Element(NS +田)
.Elements(NS +场))
{
Console.WriteLine(名称:{0};值:{1},
(字符串)element.Attribute(名称),
(字符串)element.Element(NS +值));
}
或者发现只是一个特定的元素:
的XDocument DOC = XDocument.Load(的test.xml);
NS的XNamespace =http://ns.adobe.com/xfdf/;
VAR字段= doc.Descendants(NS +田)
。凡(X =>(串)x.Attribute(名)==my_cool_id)
.FirstOrDefault();如果(场!= NULL)
{
字符串值=(字符串)field.Element(值);
//使用这里的价值
}
Can I get some help parsing the "my_cool_id" from the following xml using XDocument?
<?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>
解决方案
I suspect you're being stumped by the namespace. Try this:
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"));
}
Or to find just the one specific element:
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
}
这篇关于使用解析XML的XDocument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!