簡體   English   中英

識別單個 XML 元素並在 C# 中調用

[英]Identifying a single XML element and calling in C#

我目前有一個程序(C#)我正在使用一個 XML 文件來保存和項目及其銷售和購買價格。 但我需要弄清楚如何在我的 C# 項目中識別和調用單個部分,例如“原始機器人頭腦風暴燈泡”。

我需要能夠調用一個單獨的部分而不是整個部分。 這是我的 XML

 <items>
<Item>
  <itemName>Pristine Robot Brainstorm Bulb</itemName>
  <defindex>5701</defindex>
  <maxAmount>25</maxAmount>
  <sellPrice>4</sellPrice>
  <buyPrice>0</buyPrice>
</Item>
<Item>
  <itemName>Pristine Robot Currency Digester</itemName>
  <defindex>5700</defindex>
  <maxAmount>25</maxAmount>
  <sellPrice>4</sellPrice>
  <buyPrice>0</buyPrice>
</Item>
<Item>
  <itemName>reinforced robot emotion detector</itemName>
  <defindex>5702</defindex>
  <maxAmount>150</maxAmount>
  <sellPrice>.5</sellPrice>
  <buyPrice>0</buyPrice>
</Item>
<Item>
  <itemName>reinforced robot humor suppression pump</itemName>
  <defindex>5703</defindex>
  <maxAmount>150</maxAmount>
  <sellPrice>.5</sellPrice>
  <buyPrice>0</buyPrice>
</Item>

只需使用 Linq to Xml 根據子元素的任何值查詢您要查找的特定節點。

var xDoc = XDocument.Parse("<my xml>");

string itemName = "Pristine Robot Brainstorm Bulb";

var item = xDoc.Root.Elements("Item")
               .FirstOrDefault(x=>x.Element("itemName").Value == itemName);

如果您的目標是從 .cs 文件中調用它們,那么只需為您的元素命名即可。

<Item x:Name = "P_R_C_Register">
  <itemName>Pristine Robot Currency Digester</itemName> //and so on...

然后,當您編寫 C# 代碼時,intellisense 將向您顯示您的元素。 我希望我理解你的問題是正確的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM