在C#中使用“fields& values”读取XML

时间:2015-02-02 07:18:58

标签: c# xml xml-parsing

我们如何在C#中读取如下所示的XML,以便我们列出所有字段&他们相应的价值观。

<document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xmlns="http://ocrsdk.com/schema/recognizedBusinessCard-1.0.xsd"       xsi:schemaLocation="http://ocrsdk.com/schema/recognizedBusinessCard-1.0.xsd   http://ocrsdk.com/schema/recognizedBusinessCard-1.0.xsd">
<businessCard>
 <field type="Phone">
  <value>+91-1234 53789</value>
 </field>
 <field type="Email">
  <value>xyz@xyz.com</value>
 </field>
 <field type="Name">
  <value>My Full Name</value>
 </field>
<field type="Company">
 <value>My Company Name</value>
</field>
<field type="Job">
 <value>Technical Lead</value>
</field>
<field type="Text">
 <value>
  My Name Technical Lead Q +91-1234-567-890 © xyz@xyz.com ▲
 </value>
</field>

  

2 个答案:

答案 0 :(得分:2)

我会将XML读入Dictionary<string, string>。密钥为field type,值为<value>的内容。

XNamespace bc = "http://ocrsdk.com/schema/recognizedBusinessCard-1.0.xsd";
var fields = doc
   .Element(bc + "businessCard")
   .Elements(bc + "field")
   .ToDictionary(
       x => x.Attribute("type").Value, // key
       x => x.Element(bc + "value").Value);  // value

答案 1 :(得分:1)

我认为,这可能对您有所帮助 -

//this counter lets you count number of business cards
int iCounter = 1;
//Namespace associated with your businessCards
XNamespace xn = "http://ocrsdk.com/schema/recognizedBusinessCard-1.0.xsd";
//Dictionary containing business cards with fields as their values.
var lists = xd.Elements(xn + "businessCard").ToDictionary(key => iCounter++, bus => bus.Elements(xn + "field").
            ToDictionary(key => key.Attribute("type").Value, value => value.Element(xn + "value").Value));