简体   繁体   English

使用 C# 解析 XML 文件

[英]Parse XML file using C#

I am new to XML.我是 XML 的新手。 I need to parse this XML and read the values from the -Field- element and -name- attribute.我需要解析这个 XML 并从 -Field- 元素和 -name- 属性中读取值。

I need values from accountID, deviceID, odometerKM我需要来自 accountID、deviceID、odometerKM 的值

Here is the XML:这是 XML:

<GTSResponse command="dbget" result="success">
    <Record table="EventDataView" partial="true">
        <Field name="accountID" primaryKey="true" alternateKeys="adtkey,driverkey">
            <![CDATA[salesdemo]]>
        </Field>
        <Field name="deviceID" primaryKey="true" alternateKeys="adtkey">
            <![CDATA[bubba_polaris]]>
        </Field>
        <Field name="timestamp" primaryKey="true" alternateKeys="adtkey,driverkey">1605919705</Field>
        <Field name="statusCode" primaryKey="true">0xF010</Field>
        <Field name="latitude">0.0</Field>
        <Field name="longitude">0.0</Field>
        <Field name="odometerKM">0.2566422</Field>
        <Field name="odometerOffsetKM">0.0</Field>
    </Record>
    <Record table="EventDataView" partial="true">
        <Field name="accountID" primaryKey="true" alternateKeys="adtkey,driverkey">
            <![CDATA[salesdemo]]>
        </Field>
        <Field name="deviceID" primaryKey="true" alternateKeys="adtkey">
            <![CDATA[bubba_polaris]]>
        </Field>
        <Field name="timestamp" primaryKey="true" alternateKeys="adtkey,driverkey">1605919705</Field>
        <Field name="statusCode" primaryKey="true">0xF010</Field>
        <Field name="latitude">0.0</Field>
        <Field name="longitude">0.0</Field>
        <Field name="odometerKM">0.23445323</Field>
        <Field name="odometerOffsetKM">0.0</Field>
    </Record>
</GTSResponse>

Here is the code I have tried:这是我尝试过的代码:

XDocument doc = XDocument.Parse(receivedResponse);

Dictionary<string, string> dataDictionary = new Dictionary<string, string>();

foreach (XElement element in doc.Descendants().Where(p => p.HasElements == false))
{
    int keyInt = 0;
    string keyName = element.Name.LocalName;

    while (dataDictionary.ContainsKey(keyName))
    {
        keyName = element.Name.Namespace.ToString();

        keyName = element.Name.LocalName + "_" + keyInt++;
    }

    dataDictionary.Add(keyName, element.Value);
}

foreach (var x in dataDictionary)
{
    Console.WriteLine("keyName: " + x.Key + " value: " + x.Value);
}

When I run this, it loops through all of the -Field- elements but it does not use the -name-.当我运行它时,它会遍历所有 -Field- 元素,但它不使用 -name-。 I need to see the -name- so I know what value I have.我需要查看 -name- 以便我知道我有什么价值。 I will be updating my database and need to loop through and update fields accordingly by name.我将更新我的数据库,并且需要按名称相应地循环和更新字段。

There's a Record element that you didn't navigate through.有一个您没有浏览过的Record元素。

Try this:尝试这个:

var values =
    doc
        .Root
        .Elements("Record")
        .SelectMany((x, n) => x.Elements("Field").Select(y => new { field = y, index = n }))
        .ToDictionary(
            x => $"{(string)x.field.Attribute("name")}_{x.index}",
            x => (string)x.field);

I get this from your sample data:我从你的样本数据中得到这个:

价值观


I think you're better off with this:我认为你最好这样做:

Dictionary<int, Dictionary<string, string>> values =
    doc
        .Root
        .Elements("Record")
        .Select((x, n) => (x, n))
        .ToDictionary(
            y => y.n,
            y => y.x
                .Elements("Field")
                .ToDictionary(
                    z => (string)z.Attribute("name"),
                    z => (string)z));

Then you get:然后你得到:

值 2

Try following:尝试以下操作:

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.IO;
namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            string receivedResponse = File.ReadAllText(FILENAME);
            
            XDocument doc = XDocument.Parse(receivedResponse);

            Dictionary<string, Dictionary<string, List<Field>>> dataDictionary = doc.Descendants("Record")
                .GroupBy(x => (string)x.Attribute("table"), y => y)
                .ToDictionary(x => x.Key, y => y.Elements("Field")
                    .GroupBy(a => (string)a.Attribute("name"), b => new Field(b))
                    .ToDictionary(a => a.Key, b => b.ToList()));
        }
    }
    public class Field
    {
        public string name { get; set; }
        public Boolean? primaryKey { get; set; }
        public string alternateKeys { get; set; }
        public string text { get; set; }

        public Field(XElement field)
        {
            name = (string)field.Attribute("Field");
            primaryKey = (field.Attribute("primaryKey") == null) ? null : (Boolean?)field.Attribute("primaryKey");
            alternateKeys = (field.Attribute("alternateKeys") == null) ? null : (string)field.Attribute("alternateKeys");
            text = (string)field;
        }
    }
 
}

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

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