C# 使用树视图路径从 XDocument 获取 XElement 属性
C# get XElement attributes from XDocument with treeview path
我正在尝试编写一个 winforms 应用程序,它在 TreeView 中显示任何打开的 XML 文件节点(并且只有它的节点)并分别显示所选节点的属性(所选节点是指在TreeView)(例如显示在列表框中)。我试图通过使用以下代码来实现这一点,但它抛出一个异常说:'family\parent' 有一个无效的令牌。
private void TView__AfterSelect(object sender, TreeViewEventArgs e)
{
var doc = XDocument.Load(businessLayer.InputFilepath);
XElement myElement = doc.Root.XPathSelectElement(TView_.SelectedNode.FullPath);
try
{
foreach (var attribute in myElement.Attributes())
{
listBox1.Items.Add(attribute.Value);
}
}
catch (Exception)
{
}
}
我正在使用以下 XML 文件:
<?xml version="1.0" encoding="utf-8" ?>
<family>
<parent>
<id>grandfather</id>
<parent>
<id>father</id>
<parent>
<id>brother</id>
<child>
<id>niece</id>
</child>
</parent>
<parent>
<is>me</is>
<child>
<id>son</id>
</child>
<child>
<id>dauhter</id>
</child>
</parent>
<child>
<id>sister</id>
</child>
</parent>
<parent>
<id>uncle</id>
<parent>
<id>cousin sister</id>
<child>
<id>second cousin</id>
</child>
</parent>
<child>
<id>cousin brother</id>
</child>
</parent>
</parent>
</family>
我不知道我还能尝试什么,所以感谢您的帮助。
为避免该异常,您必须将 XML 文件路径中的每个双反斜杠替换为斜杠。
string path = treeView1.SelectedNode.FullPath.Replace('\', '/');
XElement myElement = doc.XPathSelectElement(path);
我正在尝试编写一个 winforms 应用程序,它在 TreeView 中显示任何打开的 XML 文件节点(并且只有它的节点)并分别显示所选节点的属性(所选节点是指在TreeView)(例如显示在列表框中)。我试图通过使用以下代码来实现这一点,但它抛出一个异常说:'family\parent' 有一个无效的令牌。
private void TView__AfterSelect(object sender, TreeViewEventArgs e)
{
var doc = XDocument.Load(businessLayer.InputFilepath);
XElement myElement = doc.Root.XPathSelectElement(TView_.SelectedNode.FullPath);
try
{
foreach (var attribute in myElement.Attributes())
{
listBox1.Items.Add(attribute.Value);
}
}
catch (Exception)
{
}
}
我正在使用以下 XML 文件:
<?xml version="1.0" encoding="utf-8" ?>
<family>
<parent>
<id>grandfather</id>
<parent>
<id>father</id>
<parent>
<id>brother</id>
<child>
<id>niece</id>
</child>
</parent>
<parent>
<is>me</is>
<child>
<id>son</id>
</child>
<child>
<id>dauhter</id>
</child>
</parent>
<child>
<id>sister</id>
</child>
</parent>
<parent>
<id>uncle</id>
<parent>
<id>cousin sister</id>
<child>
<id>second cousin</id>
</child>
</parent>
<child>
<id>cousin brother</id>
</child>
</parent>
</parent>
</family>
我不知道我还能尝试什么,所以感谢您的帮助。
为避免该异常,您必须将 XML 文件路径中的每个双反斜杠替换为斜杠。
string path = treeView1.SelectedNode.FullPath.Replace('\', '/');
XElement myElement = doc.XPathSelectElement(path);