简体   繁体   English

识别单个 XML 元素并在 C# 中调用

[英]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.我目前有一个程序(C#)我正在使用一个 XML 文件来保存和项目及其销售和购买价格。 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.但我需要弄清楚如何在我的 C# 项目中识别和调用单个部分,例如“原始机器人头脑风暴灯泡”。

I need to be able to call a separate section rather than the whole lot of it.我需要能够调用一个单独的部分而不是整个部分。 Here is my XML这是我的 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.只需使用 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);

If your aim is to call them from .cs file then simply give name to your elements.如果您的目标是从 .cs 文件中调用它们,那么只需为您的元素命名即可。

<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#.然后,当您编写 C# 代码时,intellisense 将向您显示您的元素。 I hope I understood your problem correct.我希望我理解你的问题是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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