![](/img/trans.png)
[英]What's the most efficient way to locate and set element values in an XDocument?
[英]Is this the most efficient way to express this XDocument query?
我們使用第三方Web服務返回XML,其外觀類似於(為簡潔起見):
<Response>
<block name="availability">
<block name="cqual">
<a name="result-code" format="text">L</a>
</block>
<block name="exchange">
<a name="code" format="text">MRDEN</a>
</block>
<block name="mqual">
<a name="rate-adaptive" format="text">G</a>
</block>
</block>
<block name="products">
<block>
<a name="product-id" format="counting">1235</a>
<block name="realms">
<block>
<a name="realm" format="text">-u@surfuk1</a>
</block>
</block>
</block>
<block>
<a name="product-id" format="counting">1236</a>
<block name="realms">
<block>
<a name="realm" format="text">-u@surfuk2</a>
</block>
</block>
</block>
<block>
<a name="product-id" format="counting">1237</a>
<block name="realms">
<block>
<a name="realm" format="text">-u@surfuk3</a>
</block>
</block>
</block>
</block>
<status no="0" />
</Response>
對於特定的產品代碼,我需要獲取realm
名稱,即內部文本:
<a name="realm" format="text">
-u @ surfuk2 </a>
因為每個元素名稱都是<block>
或<a>
所以使用linq解析xml或查詢表達式會有點麻煩。
以下是獲取特定產品領域名稱的最有效/最有效/最具表現力的方法,例如:1235:
List<XElement> products = response
.Element("Response")
.Elements("block")
.Where(x => x.Attribute("name").Value == "products")
.Elements("block").ToList();
//
// I broke down the query to aid readability
//
string realm = products.Elements("a")
.Where(x => x.Attribute("name").Value == "product-id")
.Where(y => y.Value == "1235") // hardcoded for example use
.Ancestors()
.First()
.Elements("block")
.Where(z => z.Attribute("name").Value == "realms")
.Elements("block")
.Elements("a")
.First().Value;
提供的realm
定義相當於更簡單 :
string realm = (string) products.XPathEvaluate(
"string(
/*/blocks[@name='products']
/*/a[@name='product-id' and . = '1236']
/following-sibling::block[1]
)
"
)
事實上,這比原始問題中提供的realm
的定義更具可讀性和更緊湊 。
考慮到效率 ,很可能評估單個XPath表達式也會變得更有效,但是如果發現這是真的,我們需要編寫一個應用程序來比較兩種方法的時序。
看起來是這樣,但為什么你需要所有ToList()
調用? 我看到其中三個電話,我認為不需要它們,所以它們只會減慢你的代碼速度。 但話說回來,我沒有多少使用Linq-to-XMl。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.