【发布时间】:2017-08-12 21:04:25
【问题描述】:
这是我第一次使用 XML 文件,我需要一些帮助。我对 C# 也很陌生。我创建了一个 XML 文件,其中包含基于主题的不同单词集。我想做的是仅从特定标签加载所有单词。但是,我没有收到错误,它只是跳过了应该将其添加到列表框中的代码。
这是我的 XML 文件的示例:
<?xml version="1.0"?>
<theme>
<fantasy>
<word>
<nn>wizard</nn>
<nns>wizards</nns>
<type>person</type>
</word>
<word>
<nn>wand</nn>
<nns>wands</nns>
<type>thing</type>
</word>
<word>
<vb>conjure</vb>
<vbg>conjuring</vbg>
<vbd>conjured</vbd>
</word>
<word>
<nnp>Merlin</nnp>
<type>person</type>
</word>
</fantasy>
<common>
<word>
<vb>run</vb>
<vbg>running</vbg>
<vbd>ran</vbd>
</word>
<word>
<nnp>Jeremy</nnp>
<type>person</type>
</word>
<word>
<nnp>Dylan</nnp>
<type>person</type>
</word>
<word>
<nnp>Darlene</nnp>
<type>person</type>
</word>
<word>
<nnp>Chelsea</nnp>
<type>person</type>
</word>
<word>
<jj>beautiful</jj>
<rb>beautifully</rb>
</word>
<word>
<jj>ugly</jj>
</word>
<word>
<jj>disgusting</jj>
<vbn>disgusted</vbn>
<rb>disgustingly</rb>
<nn>disgust</nn>
</word>
</common>
</theme>
我想把所有标记的标签放在一个列表框中。这是我到目前为止的代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void menuOpen_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.ShowDialog();
DocHandler.fileName = open.FileName;
DocHandler.doc = XDocument.Load(DocHandler.fileName);
txtText.Text = DocHandler.doc.ToString();
GetElements();
}
public void GetElements()
{
foreach (XElement element in DocHandler.doc.Root.Elements())
{
if (element.Name.LocalName.Contains("word"))
{
foreach (XElement subelement in element.Elements())
{
if (subelement.Name.LocalName.Contains("vb"))
{
listElements.Items.Add(subelement.Value.ToString());
}
}
}
}
}
}
public class DocHandler
{
public static string fileName { get; set; }
public static XDocument doc;
}
感谢任何帮助!
【问题讨论】:
标签: c# xml listbox linq-to-xml xelement