2012-01-20 51 views
2

检索XML节点的最快方法是什么?我有一个应用程序需要替换特定节点的功能,当文档很小时很快,但很快就会变得更大,然后需要几秒钟才能完成替换。这是方法,我只是做了一个暴力比较,在这种情况下真的很糟糕。什么是通过ID检索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; 
    } 
} 
+0

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

回答

2

尝试使用XPath:

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

你可以参考Finding Elements by Attributes in a DOM Document Using XPath更多的例子。

P.S.以小写形式启动参数名称和局部变量被认为是很好的惯例。因此,使用idReplaceunionElement而不是上面的。

+0

感谢您的建议,我已经在重构 – mjsr

相关问题