我有以下XML:改進代碼找到與使用的AttributeName和節點的節點
<TextWithNodes><Node id="0" />astralis<Node id="8" /> <Node id="9" />ltd<Node id="12" />
<Node id="14" />{<Node id="15" />DOCUMENT<Node id="23" />}<Node id="24" /> <Node id="25" />{<Node id="26" />TYPE<Node id="30" />}<Node id="31" />EX-<Node id="34" />10<Node id="36" />.<Node id="37" />12<Node id="39" /> <Node id="40" />{<Node id="41" />SEQUENCE<Node id="49" />}<Node id="50" />3<Node id="51" /> <Node id="52" />{<Node id="53" />FILENAME<Node id="61" />}<Node id="62" />e<Node id="63" />300201<Node id="69" />_<Node id="70" />ex<Node id="72" />10<Node id="74" />-<Node id="75" />12<Node id="77" />.<Node id="78" />txt<Node id="81" /> </TextWithNodes>
,我需要從編號25挑節點ID 75. XML的一部分。原始XML非常長。
我使用下面的代碼:
Dim reader As XmlTextReader = New XmlTextReader(System.Web.HttpContext.Current.Server.MapPath("~/App_Data/gate_xml_output.xml"))
reader.WhitespaceHandling = WhitespaceHandling.None
Dim xmlDoc As XmlDocument = New XmlDocument()
'Load the file into the XmlDocument
xmlDoc.Load(reader)
'Close off the connection to the file.
reader.Close()
Dim nodeList As XmlNodeList = xmlDoc.SelectNodes("//TextWithNodes/node()[preceding-sibling::Node[@id=" & startNode & "] and following-sibling::Node[@id=" & endNode & "]]")
Dim sb As StringBuilder = New StringBuilder
For Each childNode As XmlNode In nodeList
If childNode.Value IsNot Nothing Then
sb.Append(childNode.Value & " ")
End If
Next
' read the text between these nodes
ExtractText = sb.ToString
這是工作,但它是非常緩慢的。從XML獲取這些數據的任何替代方法?
請建議。
謝謝
如果文檔中的元素的「id」屬性值越來越大,那麼最快速的解決方案之一就是使用XmlReader。此外,存在一個XPath 1.0表達式,其計算結果爲O(N) - 而不是O(N^2),與您的XPath表達式一樣。請確認增加'id'值的屬性。 – 2012-02-04 05:47:35