1
這是我第一次使用XML文件,我可以使用一些幫助。我對C#也很新。我創建了一個包含基於主題的不同單詞集的XML文件。我想要做的是僅加載來自特定標籤的所有單詞。但是,我沒有收到錯誤,它只是跳過應該將其添加到列表框中的代碼。下面是我的XML文件的樣本:使用XDocument將特定標籤加載到列表框中
<?xml version="1.0"?>
<theme>
<fantasy>
<word>
<nn>wizzard</nn>
<nns>wizzards</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;
}
任何幫助表示讚賞!