读取XML文件并在组合框中显示节点

时间:2014-09-19 04:08:14

标签: c# xml

我正在尝试读取我想为我妈做的XML文件。基本上这就是我想要做的事情:

一个组合框,它将显示XML中的所有名称。

我写的XML

<Locatons.xml>
  <Name>ee</Name>
  <X>ere</X>
  <Y>erer</Y>
  <Z>re</Z>
  <Name>ee</Name>
  <X>eore</X>
  <Y>erer</Y>
  <Z>re</Z>
  <Name>878</Name>
  <X>8</X>
  <Y>4</Y>
  <Z>0</Z>
</Locatons.xml>

我写的C#代码添加到Xml文件

        xDoc.Load(path);
        XmlNode name = xDoc.CreateElement("Name");
        XmlNode x = xDoc.CreateElement("X");
        XmlNode y = xDoc.CreateElement("Y");
        XmlNode z = xDoc.CreateElement("Z");

        name.InnerText = textBox1.Text;
        x.InnerText = textBox2.Text;
        y.InnerText = textBox3.Text;
        z.InnerText = textBox4.Text;
        xDoc.DocumentElement.AppendChild(name);
        xDoc.DocumentElement.AppendChild(x);
        xDoc.DocumentElement.AppendChild(y);
        xDoc.DocumentElement.AppendChild(z);
        xDoc.Save(path);

3 个答案:

答案 0 :(得分:0)

可能这可能对你有所帮助..!  使用此名称空间:使用System.Xml.Linq;

 List<String> nameList = new List<String>();
            var NAME= XElement.Parse(xml);

           if (NAME.Attribute("Name") != null)
        {
            nameList.Add(NAME.Attribute("Name").Value);
        }

将该下拉数据源作为nameList。

答案 1 :(得分:0)

尝试这样的事情:

var str = @"
<Locatons.xml>
  <Name>ee</Name>
  <X>ere</X>
  <Y>erer</Y>
  <Z>re</Z>
  <Name>ee</Name>
  <X>eore</X>
  <Y>erer</Y>
  <Z>re</Z>
  <Name>878</Name>
  <X>8</X>
  <Y>4</Y>
  <Z>0</Z>
</Locatons.xml>";
XDocument xdoc = XDocument.Parse(str);
var output = new List<string>();
foreach (var element in xdoc.Descendants("Name"))
{
    output.Add(element.Value.ToString());
}

这会将它们全部添加到List,然后您可以填充组合框。

答案 2 :(得分:0)

如何从文件中获取名称:

var document = XDocument.Load("Locations.xml");
var names = document.Root.XPathSelectElements("/*/Name").Select(e => e.Value).ToArray();

如何将tems添加到组合框(假设您使用的是WindowsForms),名为NameBox,例如

NameBox.Items.AddRange(names);

别忘了

using System.Xml.Linq;
using System.Xml.XPath;