【问题标题】:What is the fastest way to retrieve a Xml node by ID按 ID 检索 Xml 节点的最快方法是什么
【发布时间】:2012-01-20 21:19:14
【问题描述】:

检索 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;
    }
}

【问题讨论】:

  • 你可以看看 XPath,它通常用于这样的目的。

标签: c# search tree xmlnode


【解决方案1】:

尝试使用 XPath:

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

更多示例请参考Finding Elements by Attributes in a DOM Document Using XPath

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-03
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    • 1970-01-01
    • 2010-12-25
    • 2013-06-05
    • 1970-01-01
    相关资源
    最近更新 更多