我有一個WFA運行,它需要一個XML文件並「優化」它。 我現在要添加的是檢查一個特定節點是否存在,如果沒有,顯示一條消息。c#xml尋找標題爲/的節點
的XML看起來像
<message>
<success/>
<bookings>
Some extra nodes I need not look for at this time
</bookings>
</message>
我什麼(成功)試圖做到這一點,尋找的
<success/>
存在,如果沒有找到,顯示一條消息。
我曾試圖用做到這一點的代碼是
InitializeComponent();
openFileDialog1.FileName = String.Empty; //blank filename
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
XmlDocument doc = new XmlDocument();
doc.Load(openFileDialog1.FileName);
XmlNodeList nodeToFind = doc.GetElementsByTagName("success/");
if (nodeToFind != null)
{
richTextBox2.AppendText("node found");
}
這個沒有工作,所以我通過nodeToFind做.Count之間,和值加載到一個VAR(稱爲成功)試了一下然後修改如果到
if (Successful !=0) {
display a message
}
但每次只返回0。
我猜測它可能是/中的節點名稱。
任何人都可以幫忙嗎? 感謝
編輯: 工作代碼現在看起來像
InitializeComponent();
openFileDialog1.FileName = String.Empty; //blank filename
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.PlainText);
XmlDocument doc = new XmlDocument();
doc.Load(openFileDialog1.FileName);
XmlNodeList nodeToFind = doc.GetElementsByTagName("success");
int Successfull = nodeToFind.Count;
if (Successfull == 0)
{
richTextBox2.AppendText("node NOT found");
}
}
感謝@SLaks
你應該使用'XDocument';這很容易。 – SLaks
我正在學習這個難題:-)。下一課涉及XML,我會:-) –