【问题标题】:How to Get The Values Printed from XML using LINQ or XPath如何使用 LINQ 或 XPath 获取从 XML 打印的值
【发布时间】:2015-11-29 07:16:41
【问题描述】:

我有点卡在使用 XPath 或 LINQ 从 XML 打印的值上,这也是 XPath 和 XML Parsing 的新手, 在这里查看了几个示例,但没有任何帮助,因为它们都有具有不同属性名称的 XML,对于我的情况,XML 是不同的:

<Entities TotalResult="3">
    <Entity Type="test-set-folder">
      <Fields>
          <Field Name="id">
            <Value>12457</Value>
          </Field>
          <Field Name="parent-id">
            <Value>0</Value>
          </Field>
          <Field Name="last-modified">
            <Value>2015-03-09 14:09:57</Value>
          </Field>
          <Field Name="description">
             <Value/>
          </Field>
          <Field Name="view-order"/>
          <Field Name="name">
            <Value>.NET</Value>
          </Field>
     </Fields>
   </Entity>
   <Entity Type="test-set-folder">
     <Fields>
        <Field Name="id">
           <Value>15487</Value>
        </Field>
        <Field Name="parent-id">
          <Value>0</Value>
        </Field>
        <Field Name="last-modified">
          <Value>2015-03-15 13:00:02</Value>
        </Field>
        <Field Name="description">
          <Value/>
        </Field>
        <Field Name="view-order"/>
        <Field Name="name">
          <Value>Python</Value>
        </Field>
     </Fields>
  </Entity>
</Entities>

Field 属性相同,Name 不同。

有人可以帮我打印财产的Name 及其Value

我需要遍历每个实体并打印其Name : Value

到目前为止,我已经尝试过同时使用 Xpath 和 LINQ:

var doc = XDocument.Load("XMLFile1.xml");
        foreach (var child in doc.Element("Field Name").Elements())
        {
            Console.WriteLine(child.Name);
        } 

但说真的,我对此并没有太多了解,所以我的方法是完全错误的。

我的预期输出是:

Id: 12457
parent-id: 0
last-modified:2015-03-09 14:09:57
description:
view-order:
name: .NET

和下一个实体相同。

【问题讨论】:

    标签: c# xml linq xpath


    【解决方案1】:

    您有一个数据透视表,因为您的数据是从两个标签(名称和值)中提取的。这是一种解析xml的方法

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Linq;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<Entity> cEntities = new List<Entity>();
                string input =
                    "<Entities TotalResult=\"3\">" +
                        "<Entity Type=\"test-set-folder\">" +
                          "<Fields>" +
                              "<Field Name=\"id\">" +
                                "<Value>12457</Value>" +
                              "</Field>" +
                              "<Field Name=\"parent-id\">" +
                                "<Value>0</Value>" +
                              "</Field>" +
                              "<Field Name=\"last-modified\">" +
                                "<Value>2015-03-09 14:09:57</Value>" +
                              "</Field>" +
                              "<Field Name=\"description\">" +
                                 "<Value/>" +
                              "</Field>" +
                              "<Field Name=\"view-order\"/>" +
                              "<Field Name=\"name\">" +
                                "<Value>.NET</Value>" +
                              "</Field>" +
                         "</Fields>" +
                       "</Entity>" +
                       "<Entity Type=\"test-set-folder\">" +
                         "<Fields>" +
                            "<Field Name=\"id\">" +
                               "<Value>15487</Value>" +
                            "</Field>" +
                            "<Field Name=\"parent-id\">" +
                              "<Value>0</Value>" +
                            "</Field>" +
                            "<Field Name=\"last-modified\">" +
                              "<Value>2015-03-15 13:00:02</Value>" +
                            "</Field>" +
                            "<Field Name=\"description\">" +
                              "<Value/>" +
                            "</Field>" +
                            "<Field Name=\"view-order\"/>" +
                            "<Field Name=\"name\">" +
                              "<Value>Python</Value>" +
                            "</Field>" +
                         "</Fields>" +
                      "</Entity>" +
                    "</Entities>";
    
    
                XElement entities = XElement.Parse(input);
    
                foreach (XElement entity in entities.Descendants("Entity"))
                {
                    Entity newEntity = new Entity();
                    cEntities.Add(newEntity);
    
                    foreach (XElement field in entity.Descendants("Field"))
                    {
                        string name = field.Attribute("Name").Value;
                        string value = field.Element("Value") == null ? "" : field.Element("Value").Value;
    
                        switch (name)
                        {
                            case "id" :
                                newEntity.id = int.Parse(value);
                                break;
                            case "parent-id":
                                newEntity.parent_id = int.Parse(value);
                                break;
                            case "last-modified":
                                newEntity.last_modified = DateTime.Parse(value);
                                break;
                            case "description":
                                newEntity.description = value;
                                break;
                            case "view-order":
                                newEntity.view_order = value;
                                break;
                            case "name":
                                newEntity.name = value;
                                break;
                        }
                    }
                }
    
                //write data
                foreach(Entity entity in cEntities)
                {
                    Console.WriteLine("id: {0}", entity.id);
                    Console.WriteLine("parent-id: {0}", entity.parent_id);
                    Console.WriteLine("last-modified: {0}",entity.last_modified);
                    Console.WriteLine("description: {0}",entity.description);
                    Console.WriteLine("view-order: {0}",entity.view_order);
                    Console.WriteLine("name: {0}",entity.name);
                    Console.WriteLine();
    
                }
                Console.ReadLine();
    
    
            }
            public class Entity
            {
                public int id { get; set; }
                public int parent_id { get; set; }
                public DateTime last_modified { get; set; }
                public string description { get; set; }
                public string view_order { get; set; }
                public string name { get; set; }
            }
        }
    }
    ​
    

    【讨论】:

      【解决方案2】:

      由于某些字段缺少值元素,您可以试试这个:

      XElement element = XElement.Load("XmlFile.xml"); 
      var query = from field in element.Descendants("Field")
      select new
      {
          NameAttribute = field.Attribute("Name").Value,
          Value = field.Descendants("Value").Any() ?
          field.Element("Value").Value : "No Value"
      };
      var namesAndValues = query.ToList()
      

      【讨论】:

      • 另一个设置Value的选项是(string)field.Element("Value") ?? "No Value"
      • 感谢您的回答,这几乎符合我的预期。但它不是遍历每个实体。它只是将它附加到一个平面列表中。 .反正我会做剩下的..谢谢你的回答
      【解决方案3】:

      试试这个

      var names = from r in document.Descendants("Entities")
                                      .Descendants("Entity")
                                          .Descendants("Fields")
                                              .Descendants("Field")
                  select new
                      {
                          Name = r.Element("name").Value,
                      };
      
      foreach (var n in names)
      {
          Console.WriteLine(n.Name);
      }
      

      【讨论】:

        【解决方案4】:

        你只需要遵循你的xml结构

        未经测试的代码:

        var doc = XDocument.Load("XMLFile1.xml");
        foreach (var fields in doc.Descendants("Fields")) {
        
            foreach (var field in fields.Elements("Field")) {
        
                Debug.WriteLine(string.Format("{0}: {1}", field.Attribute("Name").Value, field.Elements("Value").First().Value));
        
            }
        
        }
        

        【讨论】:

          猜你喜欢
          • 2016-03-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-04
          • 2018-05-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多