XML和C# - 帮助从某个元素中提取信息

时间:2010-02-02 19:17:12

标签: c# xml

所以我不知道如何准确地说出来,但是就在这里。现在,我的应用程序可以毫无问题地从XML中提取有关用户的信息。示例XML:

<statuses type="array">
<status>
  <id>ID1</id>
  <text>Text That I want to pull 1</text>
  <user>
    <name>User1</name>
    <screen_name>User1_Screen</screen_name>
    <location>Location_User1</location>
    <Description>User1_Description</Description>
  </user>
</status>
<status>
  <id>ID2</id>
  <text>Text That I want to pull 2</text>
  <user>
    <name>User2</name>
    <screen_name>User2_Screen</screen_name>
    <location>Location_User2</location>
    <Description>User2_Description</Description>
  </user>
</status>

将Screen_name标记拉入列表框。这里的代码提取了获取用户详细信息的信息:

    private void listBox1_SelectedValueChanged(object sender, EventArgs e)
    {
        //Load the temp file
        var doc = XDocument.Load("Temp.xml");


        var setting = doc.Descendants("user").First(a => a.Element("screen_name").Value == listBox1.Text);

        //Variables for information from XML
        var Location = setting.Element("location").Value;
        var Description = setting.Element("description").Value;
        var Screen_name = setting.Element("name").Value;

        //Info Pulled from "temp.xml"
        location.Text = "Location: "+Location;
        Username.Text = "Name: " + Screen_name;
        descriptionBox.Text = "Description: "+Description;
    }

而我现在想要的只是文本标签,而我正好想要把它搞清楚。

1 个答案:

答案 0 :(得分:1)

我没有任何问题地运行你的代码。你应该检查:

  • 您的listBox1.Text值是否正确?
  • 您是否试图以正确的路径Temp.xml进行访问?
  • 您确定Temp.xml格式正确吗(它缺少</statuses>);尝试将其打开到您的IE浏览器中。

编辑:试试这个:

var text = setting.Parent.Element("text").Value;