【问题标题】:C# XML Read All Child Nodes Of A Specific NodeC# XML 读取特定节点的所有子节点
【发布时间】:2015-03-18 17:56:53
【问题描述】:

所以我有一个程序可以读取 XML 文件中的所有名称节点并将它们添加到组合框。单击按钮后,它会接受此响应,并需要从名称所在节点的子节点获取所有其他数据。

XML 文档:

<People>
    <Person>
        <Name>Greg</Name>
        <Age>23</Age>
        <Height>200</Height>
    </Person>
    <Person>
        <Name>John</Name>
        <Age>34</Age>
        <Height>230</Height>
    </Person>
</People>

到目前为止我得到了什么:

            XmlDocument Doc = new XmlDocument();
            Doc.Load(FilePath);
            foreach (XmlNode Node in Doc.SelectNodes("People/Person"))
            {
                comboBox1.Items.Add(Node.SelectSingleNode("Name").InnerText);
            }
            string RegPicked = comboBox1.SelectedItem.ToString();

            foreach (XmlNode xNode in Doc.SelectNodes("People/Person"))
                if (xNode.SelectSingleNode("Name").InnerText == RegPicked)
                {
                    textBox1.Text = xNode.ParentNode.ChildNodes.ToString();
                }
             Doc.Save(FilePath);

当我运行代码时,我只会在文本框中看到“System.Xml.XmlChildNodes”。 我知道我做错了什么,但我不确定是什么。

【问题讨论】:

  • 它们是 XmlChildnodes(ToString() 方法使用基本的 .net ToString(),在这种情况下您将获得类型的 FullName)。您必须评估 ChildNode,如本页所述:msdn.microsoft.com/en-us/library/…
  • 你到底想在 TextBox 中做什么?
  • 奇怪的代码.. 你什么都没做。 错误

标签: c# xml winforms


【解决方案1】:

你必须区分子节点:

textBox1.Text = xNode.ParentNode.ChildNodes.SelectSingleNode("age").InnerText;

【讨论】:

  • 谢谢,我知道这是小事
【解决方案2】:

执行此操作,您将获得要搜索其值的节点的父节点内的所有元素。

 string str = @"<People>
                        <Person>
                            <Name>Greg</Name>
                            <Age>23</Age>
                            <Height>200</Height>
                        </Person>
                        <Person>
                            <Name>John</Name>
                            <Age>34</Age>
                            <Height>230</Height>
                        </Person>
                    </People>";

        XDocument xdoc = XDocument.Parse(str);
        var xmlURL = (from el in xdoc.Descendants("Name")
                     where el.Value == "John"
                     select el.Parent).First().ToString();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-22
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多