简体   繁体   中英

Identifying a single XML element and calling in C#

I currently have a program(C#) I am working on that uses an XML file to keep and item and its sell and buy price. But I need to figure out how to identify and call just a single section such as the "pristine Robot Brainstorm Bulb" in my C# project.

I need to be able to call a separate section rather than the whole lot of it. Here is my 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>

Just use Linq to Xml to query for the specific node that you are looking for, based the any of the values of the child elements.

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);

If your aim is to call them from .cs file then simply give name to your elements.

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

Then intellisense will show you your element when you are coding C#. I hope I understood your problem correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM