0

我有一个如下所示的 XML 文件:

<Directories>
    <directory name="name1" info="blahblah" otherInfo="blahblah">
        <file fileName="name"  path="" />
    </directory>

    <directory name="name2" info="blahblah" otherInfo="blahblah">
        <file fileName="name"  path="" />
    </directory>

    <directory name="name3" info="blahblah" otherInfo="blahblah">
        <file fileName="name"  path="" />
    </directory>
</Directories>

我正在使用以下代码解析相关分支以更新目录/文件信息:

XmlDocument objLog = new XmlDocument();
objLog.Load(path);

//update directory info
foreach (XmlNode objNode in objLog.SelectNodes("/Directories/directory"))
{
    XmlElement objUpdatedNode = objLog.CreateElement("directory");
    objUpdatedNode.SetAttribute("name", "NAME");
    objUpdatedNode.SetAttribute("info", "INFO");
    objUpdatedNode.SetAttribute("otherInfo", "OTHERINFO");

    //update file information
    foreach (XmlNode objFileNode in 
             objLog.SelectNodes("/Directories/directory/file"))
    {
        XmlElement objFileNode = objLog.CreateElement("file");
        objFileNode.SetAttribute("fileName", "FILENAME");
        objFileNode.SetAttribute("path", "PATH");

        objLog.SelectNodes("/Directories")[0]
              .ReplaceChild(objUpdatedNode, objNode);         
        objUpdatedNode.AppendChild(objUpdatedFileNode);
    }

    objLog.Save(path);
}

如果 XML 文件中只有目录,则代码的工作方式与我预期的一样,但是如果我有多个上述条目,则会引发错误,因为它尝试多次解析文件节点并且 XML 文件永远不会更新. 如果我去掉代码的更新文件信息部分,目录分支会正确更新。如何更新目录及其关联的内部文件分支?

4

1 回答 1

2

您不需要创建/删除元素。只需按如下方式更新它们

XmlDocument objLog = new XmlDocument();
objLog.Load(path);

//update directory info
foreach (XmlElement objNode in objLog.SelectNodes("/Directories/directory"))
{
    objNode.SetAttribute("name", "NAME");
    objNode.SetAttribute("info", "INFO");
    objNode.SetAttribute("otherInfo", "OTHERINFO");

    //update file information
    foreach (XmlElement objFileNode in objNode.ChildNodes)
    {
        objFileNode.SetAttribute("fileName", "FILENAME");
        objFileNode.SetAttribute("path", "PATH");
    }
}

// Done Updating - Save
objLog.Save(path);

我已经更改了foreach要使用的循环XmlElement,使您可以访问SetAttribute方法。循环只是遍历节点并更新。

于 2013-09-23T14:22:22.750 回答