2

检索 XML 节点的最快方法是什么?我有一个应用程序需要替换特定节点的功能,当文档很小但很快变大时,需要几秒钟才能完成替换。这就是方法,我只是做了一个蛮力比较,在那种情况下真的很糟糕。

public bool ReplaceWithAppendFile(string IDReplace)
{
    XElement UnionElement = (from sons in m_ExtractionXmlFile.Root.DescendantsAndSelf()
                             where sons.Attribute("ID").Value == IDReplace
                             select sons).Single();
    UnionElement.ReplaceWith(m_AppendXmlFile.Root.Elements());
    m_ExtractionXmlFile.Root.Attribute("MaxID").Value =
        AppendRoot.Attribute("MaxID").Value;
    if (Validate(m_ExtractionXmlFile, ErrorInfo))
    {
        m_ExtractionXmlFile.Save(SharedViewModel.ExtractionFile);
        return true;
    }
    else
    {
        m_ExtractionXmlFile = XDocument.Load(SharedViewModel.ExtractionFile);
        return false;
    }
}
4

1 回答 1

2

尝试使用 XPath:

string xPath = string.Format("//*[@id='{0}']", IDReplace);
XElement UnionElement = m_ExtractionXmlFile.XPathSelectElement(xPath);

您可以参考使用 XPath 在 DOM 文档中按属性查找元素以获取更多示例。

PS 以小写开头的参数和局部变量的名称被认为是一个很好的约定。因此,使用idReplaceandunionElement而不是上面的。

于 2012-01-20T22:05:50.173 回答