2012-01-20 50 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

相關問題