查询 XML 以提取一条记录并将数据绑定到各个文本块
我是新手,所以请耐心等待。使用 C# 和 LINQ,我尝试从 XML 文件中提取一条记录,并且希望将其元素和属性绑定到各个文本块。
假设我有一个名为 Test.xml 的 xml 文件:
<Data>
<Test id=1>
<Text>"First Record"</Text>
</Test>
<Test id=2>
<Text>"Second Record"</Text>
</Test>
<Data>
我想传递一个 id 变量,这样我就可以提取该记录信息并将其绑定到各个文本块
var r = 2 // just hardcoding for the example
XDocument d = XDocument.Load("Test.xml");
var q = from t in d.Descendants("Test")
where t.Attribute("id").Value == r
select new
{
id = t.Attribute("id").Value,
text = t.Element("text").Value
}
现在我想将“id”和“text”绑定到单独的文本块
idTextBlock.Text = id
textTextBlock.Text = text
这当然会引发有关 id 和文本“在此上下文中不存在”的各种错误。我见过的所有示例都只是将输出集中到控制台上的单个字符串,这对我没有帮助。我对编程真的很陌生(第二周),所以我可能做的完全错误。任何帮助将不胜感激。谢谢!
I'm new at this so bear with me. Using C# and LINQ, I am trying to pull out one record from an XML file and I want to bind it's Elements and Attributes to individual textblocks.
Lets say I have this xml file named Test.xml:
<Data>
<Test id=1>
<Text>"First Record"</Text>
</Test>
<Test id=2>
<Text>"Second Record"</Text>
</Test>
<Data>
I want to pass in a variable for the id so i can pull out that records information and bind it to individual textblocks
var r = 2 // just hardcoding for the example
XDocument d = XDocument.Load("Test.xml");
var q = from t in d.Descendants("Test")
where t.Attribute("id").Value == r
select new
{
id = t.Attribute("id").Value,
text = t.Element("text").Value
}
Now I would like to bind "id" and "text" to indivual Text blocks
idTextBlock.Text = id
textTextBlock.Text = text
This of course throws up all sorts of errors about id and text "not existing in this context". All the examples I have seen have simply put the output lumped to a single string on the console which doesn't help me. I am really new (2nd week) to programming so I may be doing this completely wrong. ANY assistance would be appreciated. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我已经更正了您提供的 XML,以使下面的查询正常工作。
更正的 XML:(闭合的
Data
标记,id 属性值用双引号引起来)I've corrected XML you've provided to get query below worked.
Corrected XML: (Closed
Data
tag, id attribute value enclosed in double quotes)