【问题标题】:XML get deleted in C#XML在C#中被删除
【发布时间】:2017-07-15 05:09:06
【问题描述】:

我正在尝试仅删除 ID 与 lstBox 选定索引匹配的 XML 元素 <Contact>。代码运行,然而,它实际上删除了我的 XML 文件中的所有内容,所以我留下了一个空的 txt 文件。我有这样的代码:

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>sallyp@hotmail.com</Email>
    </Contact>
    <Contact>
        <ID>gresul</ID>
        <FirstName>Greg</FirstName>
    <LastName>Sullivan</LastName>
        <Mobile>0432928381</Mobile>
        <Email>gregsul@outlook.com</Email>
    </Contact>
    <Contact>
        <ID>chrmac</ID>
        <FirstName>Christie</FirstName>
    <LastName>Mack</LastName>
        <Mobile>0421231231</Mobile>
        <Email>christiemack@gmail.com</Email>
    </Contact>
</Contacts>

列表框选择为蓝色。

不确定是否相关,但这是我的整个文件 here 的 pastebin

感谢您对此事的任何帮助。

【问题讨论】:

  • 你在用c#吗?
  • 在您的 XML 文件中,&lt;ID&gt;...&lt;/ID&gt;XML 元素 而不是 XML 属性,因此 (string)x.Attribute("ID") == lstBox.SelectedItem.ToString() 将始终为 false。而且,事实上,在测试中似乎没有任何东西被删除。所以我怀疑问题实际上出在updateXMLFile(xdoc);。你能分享那个代码吗?
  • 演示小提琴在尝试删除 ID 为 "chrmac": dotnetfiddle.net/T6ffsH 的元素时显示未删除任何内容
  • 您好,感谢您的回复。整个代码在这里pastebin.com/ftjtie8A
  • updateXMLFile() 中,您可以捕获并吞下所有异常。与其这样做,不如报告或记录它们!如果 FileIO.WriteTextAsync(file, xdoc.ToString()); 以某种方式抛出异常,那么结果可能是一个不完整的文件。

标签: c# xml xamarin


【解决方案1】:

但是,您可以使用xmlNode。我已经完成了类似的要求,并通过像这样使用xmlNode 来修复

 XmlTextReader reader = new XmlTextReader(path);

    XmlDocument doc = new XmlDocument();
    XmlNode node = doc.ReadNode(reader);

    foreach (XmlNode chldNode in node.ChildNodes)
    {
        string employeeName = chldNode.Attributes["Name"].Value;
        if (employeeName == Employee)
        {                    
            //******your code here
        }
    }

虚拟 XML

 <Root>
    <Employee Name ="TestName">
    <Childs/>
 </Root>

我参考了here。在您的上下文中,如果匹配,您可以删除子节点。

希望对你有帮助。

【讨论】:

    【解决方案2】:

    我从你们所有人那里得到了答案,这最终奏效了。

    private async void updateXMLFile(XDocument xdoc)
            {
                try
                {
                    //StorageFile file = await installedLocation.CreateFileAsync("Contacts.xml", CreationCollisionOption.ReplaceExisting);
                    StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync("Contacts.xml"); //This line was the replacement for the one above.
                    await FileIO.WriteTextAsync(file, xdoc.ToString());
                }
                catch (Exception ex)
                {
                    String s = ex.ToString();
                }
            }
    

    也由x.Attribute to x.Element改成

    感谢所有帮助过的人。

    【讨论】:

      【解决方案3】:
      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)
              {
                  var id = lstBox.SelectedItem.ToString();
                  XmlNode node = xdoc.SelectSingleNode(string.Format("/Contacts/Contact[@ID='{0}']", id));
      
                  if (node != null)
                  {
                      XmlNode parent = node.ParentNode;
                      parent.RemoveChild(node);
                      updateXMLFile(xdoc);
                  }
              }
          }
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 2015-02-21
      • 1970-01-01
      相关资源
      最近更新 更多