[英]Get value in xml from c#
這個問題一定很容易,但是我遇到了一個我無法解決的問題。 無論我嘗試什么,我都無法使用linq解析此xml並獲取xml值。
錯誤為“ System.Collections.Generic.IEnumerable”不包含“元素”的定義,並且找不到擴展方法“元素”接受類型為“ System.Collections.Generic.IEnumerable”的第一個參數(您是否丟失了?使用指令或程序集引用?)”
我想找到Xelement attribute.value,它的孩子有一個具體的attribute.value。 如何獲取attribute.value?
謝謝
XML文件
<submitInfo>
<setting name="file1" file ="example3.c" info ="open it!" serializeAs="String">
<add name="file11" program="example2.c" />
<add name="file12" value="example1.c" />
<value />
<setting name="file2" file ="example23.c" info ="open it!" serializeAs="String">
<add name="file21" program="example22.c" />
<add name="file22" value="example21.c" />
<value />
</setting>
</submitInfo>
碼:
var title1 = from q in doc.Element("content").Element("submitInfo").Elements("setting")
select q;
foreach (var t1 in title1)
{
Console.WriteLine(
String.Format(
name = title1.Element("name").Value,
file= title1.Element("file").Value,
info= title1.Attribute("info").Value));
}
//get setting info
var title = from p in doc.Element("content").Element("submitInfo").Element("setting").Elements("add")
select p;
foreach (var t1 in title)
{
Console.WriteLine(
String.Format(
name = title1.Element("name").Value,
value = title1.Element("program").Value));
這是一個問題:
name = title1.Element("name").Value,
file= title1.Element("file").Value,
info= title1.Attribute("info").Value));
查看您的XML:
<setting name="file1" file ="example3.c" info ="open it!" serializeAs="String">
<add name="file11" program="example2.c" />
<add name="file12" value="example1.c" />
<value />
</setting>
它沒有name
或file
元素-它們是屬性。 所以你想要像這樣的東西:
string name = t1.Attribute("name");
string file = t1.Attribute("file");
string info = t1.Attribute("info");
請注意,這使用的是t1
,而不是title1
否則,您要從查詢中獲取數據,而不是查詢中的特定元素。
此外,您在這里確實不需要查詢表達式。 只需使用:
var title1 = doc.Element("content").Element("submitInfo").Elements("setting");
另一個問題是您當前正在調用string.Format
其中包含三個分配。 我懷疑您實際上想要的是:
Console.WriteLine("{0} {1} {2}", t1.Attribute("name"),
t1.Attribute("file"), t1.Attribute("info"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.