我想刪除XML元素<Contact>
其中ID與lstBox選定索引相匹配。代碼運行,但是,它實際上刪除了我的XML文件中的所有內容,所以我留下了一個空的txt文件。我有這樣的代碼:XML在C#中被刪除
private async void btnDeleteContact_Click(object sender, RoutedEventArgs e)
{
StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("Contacts.xml");
XDocument xdoc = XDocument.Load(file.Path);
if (lstBox.SelectedIndex != -1)
{
xdoc.Element("Contacts")
.Elements("Contact")
.Where(x => (string)x.Attribute("ID") == lstBox.SelectedItem.ToString()).Remove();
lstBox.SelectedIndex = -1;
updateXMLFile(xdoc);
}
}
這是我的XML文件
<?xml version="1.0" encoding="UTF-8" ?>
<Contacts>
<Contact>
<ID>salpea</ID>
<FirstName>Sally</FirstName>
<LastName>Pearson</LastName>
<Mobile>0431529562</Mobile>
<Email>[email protected]</Email>
</Contact>
<Contact>
<ID>gresul</ID>
<FirstName>Greg</FirstName>
<LastName>Sullivan</LastName>
<Mobile>0432928381</Mobile>
<Email>[email protected]</Email>
</Contact>
<Contact>
<ID>chrmac</ID>
<FirstName>Christie</FirstName>
<LastName>Mack</LastName>
<Mobile>0421231231</Mobile>
<Email>[email protected]</Email>
</Contact>
</Contacts>
列表框選擇是藍色的。
不知道這是否是相關的,但是這是我的整個文件here
感謝有關此事的任何幫助引擎收錄。
你使用的是C#嗎? –
在您的XML文件中,' ... '是* XML元素*而不是* XML屬性*所以'(string)x.Attribute(「ID」)== lstBox.SelectedItem.ToString()'將永遠是假的。事實上,在測試中似乎沒有任何東西被移除。所以我懷疑問題實際上是在'updateXMLFile(xdoc);'中。你可以分享該代碼嗎? –
dbc
嘗試刪除ID爲「chrmac」的元素時,演示提琴沒有顯示任何內容:https://dotnetfiddle.net/T6ffsH – dbc