我有一个简单的窗口,其中XML节点作为项目加载到ListBox。现在,我想通过从该列表框中选择一个项目并单击删除按钮来删除某些节点。
我尝试将所选项目存储到变量,如果InnerText在XML中的值与ListBox中所选项目的值相同,将进行比较。但是肯定有问题,因为它不起作用。
C#代码:
static string projectDirectory = Directory.GetParent(workingDirectory).Parent.FullName;
static string xmlLocation = System.IO.Path.Combine(projectDirectory, "SubjectList.xml");
string selectedSubjectItem;
private void DeleteSubjectButton_Click(object sender, RoutedEventArgs e)
{
XmlDocument document = new XmlDocument();
document.Load(xmlLocation);
foreach(XmlNode node in document.SelectNodes("Subjects/Subject"))
{
if (node.SelectSingleNode("Subject").InnerText == selectedSubjectItem)
{
node.ParentNode.RemoveChild(node);
}
document.Save(xmlLocation);
}
}
private void SubjectList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
selectedSubjectItem = SubjectList.SelectedItem.ToString();
}
XAML代码:
<Grid>
<Grid.Resources>
<XmlDataProvider x:Key="SubjectData" Source="SubjectList.xml" XPath="/Subjects/Subject"/>
</Grid.Resources>
<DockPanel Margin="10">
<StackPanel DockPanel.Dock="Right" Margin="10,0,0,0">
<Button Name="AddSubjectButton" Margin="0,0,0,5" Click="AddSubjectButton_Click">Add</Button>
<Button Name="DeleteSubjectButton" Click="DeleteSubjectButton_Click">Delete</Button>
</StackPanel>
<StackPanel DockPanel.Dock="Left">
<ListBox x:Name="SubjectList" Margin="0,0,0,0" ItemsSource="{Binding Source={StaticResource SubjectData}}" ScrollViewer.VerticalScrollBarVisibility="Visible" Height="175" SelectionChanged="SubjectList_SelectionChanged"></ListBox>
<TextBox x:Name="InputNewSubject" Text="Input new subject..."/>
</StackPanel>
</DockPanel>
</Grid>
</Window>
XML文件:
<?xml version="1.0" encoding="utf-8"?>
<Subjects>
<Subject>Subject1</Subject>
<Subject>Subject2</Subject>
<Subject>Subject3</Subject>
</Subjects>
答案 0 :(得分:0)
我认为您的节点选择有误。你尝试过吗?
com.android.support
我还将AndroidX
移到foreach循环的下面,这样该文档将只保存一次。
答案 1 :(得分:0)
SubjectList.SelectedItem.ToString()
将返回“ System.Xml.XmlElement”。您应该将SelectedItem
强制转换为XmlElement
并访问其InnerText
属性以获取实际值:
private void SubjectList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
selectedSubjectItem = (SubjectList.SelectedItem as XmlElement)?.InnerText;
}
然后您可以将其与节点的InnerText
进行比较:
private void DeleteSubjectButton_Click(object sender, RoutedEventArgs e)
{
XmlDocument document = new XmlDocument();
document.Load(xmlLocation);
foreach (XmlNode node in document.SelectNodes("Subjects/Subject"))
{
if (node.InnerText == selectedSubjectItem)
{
node.ParentNode.RemoveChild(node);
}
}
document.Save(xmlLocation);
}
还请注意,在Save
循环之后,您应该只调用一次foreach
方法。