我有以下XML结构:
<?xml version="1.0" encoding="utf-8"?>
<xml>
<root>
<Item>
<taxids>
<string>330</string>
<string>374</string>
<string>723</string>
<string>1087</string>
<string>1118</string>
<string>1121</string>
</taxids>
</Item>
</root>
</xml>
我需要将xml文件中的所有字符串节点都添加到字符串变量中,如下所示:
var query = from ip in doc.XPathSelectElements("xml/root/Item")
where ip.XPathSelectElement("taxid").Value == "723"
select ip.XPathSelectElements("taxids").ToString();
但我在变量query
的一行中得到以下内容:
"System.Xml.XPath.XPathEvaluator+<EvaluateIterator>d__0`1[System.Xml.Linq.XElement]"
我想得到一个这样的字符串:
<taxids><string>330</string><string>374</string><string>723</string><string>1087</string><string>1118</string><string>1121</string></taxids>
这可能吗?
谢谢!
答案 0 :(得分:1)
我建议你这样的事情:
var values = from ids in doc.XPathSelectElements("/xml/root/Item/taxids")
from id in ids.XPathSelectElements("string")
where id.Value.Contains("723")
select ids.ToString();
var result = string.Join("", values);
value
变量将包含所有出租车,其中至少有一个string
子项的值为723
。
另一种变体,它不会为子项检查使用XPath:
var values = from ids in doc.XPathSelectElements("/xml/root/Item/taxids")
from id in ids.Elements("string")
where id.Value.Contains("723")
select ids.ToString();
var result = string.Join("\n", values);
答案 1 :(得分:0)
var doc = XDocument.Parse(@"<?xml version=""1.0"" encoding=""utf-8""?>
<xml>
<root>
<Item>
<taxids>
<string>330</string>
<string>374</string>
<string>723</string>
<string>1087</string>
<string>1118</string>
<string>1121</string>
</taxids>
</Item>
</root>
</xml>");
var query = doc.XPathSelectElement("xml/root/Item/taxids");
Console.WriteLine(query);