XPath异常SelectSingleNode

时间:2011-08-22 06:12:50

标签: c# xml xpath

private void toolStripButton2_Click(object sender, EventArgs e)
{
        XmlTextReader reader = new XmlTextReader("component.xml");
        XmlDocument doc = new XmlDocument();
        doc.Load(reader);
        string path4 = treeView1.SelectedNode.FullPath.ToString();

        XmlNode nodeToRemove = doc.SelectSingleNode(path4);
        XmlNode parentNode = nodeToRemove.ParentNode;
        parentNode.RemoveChild(nodeToRemove);
 }

我在xml中使用以下代码删除节点,但会产生以下错误。请帮帮我。

这是我的xml的一部分。我想删除用户选择的路径条目。对于选择路径,我生成了树视图。变量path4来自树视图选择的路径。

<WindowEntries>
<WindowEntry>
  <Name>tbwUnitOverview</Name>
  <View>TRN_UNIT</View>
  <LU>TrnUnit</LU>
  <DefaultWindowText />
  <Flags>0</Flags>
</WindowEntry>
<WindowEntry>
  <Name>tbwBrandOverView</Name>
  <View>TRN_BRAND</View>
  <LU>TrnBrand</LU>
  <DefaultWindowText />
  <Flags>0</Flags>
</WindowEntry>
<WindowEntry>
  <Name>tbwProductCategory</Name>
  <View>TRN_PROD_CATEGORY</View>
  <LU>TrnProdCategory</LU>
  <DefaultWindowText />
  <Flags>0</Flags>
</WindowEntry>
<WindowEntry>
  <Name>tbwModel</Name>
  <View>TRN_MODEL</View>
  <LU>TrnModel</LU>
  <DefaultWindowText />
  <Flags>0</Flags>
</WindowEntry>
</WindowEntries>

error window error2

3 个答案:

答案 0 :(得分:1)

仅供参考,代码应为

using (XmlReader reader = XmlReader.Create("component.xml"))
{
    XmlDocument doc = new XmlDocument();
    doc.Load(reader);
    string path4 = treeView1.SelectedNode.FullPath.ToString();

    // now replace '\' by '/'
    path4 = path4.Replace('\\', '/');

    XmlNode nodeToRemove = doc.SelectSingleNode(path4);
    XmlNode parentNode = nodeToRemove.ParentNode;
    parentNode.RemoveChild(nodeToRemove);
}
  1. 除非您仍在使用.NET 1.1,否则请勿使用new XmlTextReader()。它已替换为XmlReader.Create()
  2. 您需要在阅读器周围设置using块,以确保清理它,无论例外情况如何。

答案 1 :(得分:0)

正如Mark Hosang所说,这是因为您使用\代替/。 试试:

path4 = path4.Replace("\\", "/");

这应该可以解决问题;)

答案 2 :(得分:0)

Xpath必须格式正确:/node1/node2/.../nodeN
像这样修复,它有效:)

        XmlTextReader reader = new XmlTextReader("data.xml");
        XmlDocument doc = new XmlDocument();
        doc.Load(reader);
        string path4 = treeView1.SelectedNode.FullPath.ToString();       

        // now replace '\' by '/'
        path4 = path4.Replace('\\', '/');
        // appending '/' at beginning
        path4 = "/" + path4;           

        XmlNode nodeToRemove = doc.SelectSingleNode(path4);
        XmlNode parentNode = nodeToRemove.ParentNode;
        parentNode.RemoveChild(nodeToRemove);


请参阅Xpath语法:http://www.w3schools.com/xpath/xpath_syntax.asp