使用Linq to XML从XML文件中按属性名获取所有属性值

本文关键字:属性 XML 获取 to Linq 文件 使用 | 更新日期: 2023-09-27 18:14:28

我有一个XML文件,我必须从XML中提取所有属性值。我已经尝试了下面的一个,但我需要它在Linq。谁能指导我怎么做这件事?

示例XML

<MapFile>
 <Import>
  <field name1="BorrowId" name2="EMPLID" />
  <field name1="Firstname" name2="COMPLETENAME" />
  <field name1="Address" name2="Address" Reference="Location" />
 </Import>
 <Location>
  <Lookup Key="CC" Replace="1" />
  <Lookup Key="CE" Replace="2" />
 </Location>
</MapFile>

预期结果

[0]:
  CurrentVal = "BorrowId"
  NewVal = "EMPLID"
  Reference = null
  ReferenceList = null
[1]:
  CurrentVal = "Firstname"
  NewVal = "COMPLETENAME"
  Reference = null
  ReferenceList = null
[2]:
  CurrentVal = "Address"
  NewVal = "Address"
  Reference = "Location"
  ReferenceList = [0]:
                       Key = "CC"
                       Value = "1"
                  [1]:
                       Key = "CE"
                       Value = "2"

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@sPath);
var attrValues = xmlDoc.GetElementsByTagName("field");
List<MapFileModel> MapFileMod = new List<MapFileModel>();
foreach (XmlNode x in attrValues)
{
   MapFileModel _objMapFile = new MapFileModel();
   if (x.Attributes["name1"] != null)
   {
      _objMapFile.CurrentVal = x.Attributes["name1"] != null ? x.Attributes["name2"].Value : null;
      _objMapFile.NewVal = x.Attributes["name2"] != null ? x.Attributes["name2"].Value : null;
      _objMapFile.Reference = x.Attributes["Reference"] != null ? x.Attributes["Reference"].Value : null;
    }
   MapFileMod.Add(_objMapFile);
}

使用Linq to XML从XML文件中按属性名获取所有属性值

好的,看起来你想要这样的东西,它加载Import根下元素的所有field元素,然后通过查找不是 Import的每个元素来加载引用列表。

var doc = XDocument.Load("foo.xml");
var replacements = doc
    .Root
    .Element("Import")
    .Elements("field")
    .Select(x => new Replacement {
        CurrentValue = (string) x.Attribute("name1"),
        NewValue = (string) x.Attribute("name2"),
        Reference = (string) x.Attribute("reference")
    })
    .ToList();
var referenceLists = doc
    .Root
    .Elements()
    .Where(f => f.Name.LocalName != "Import")
    .ToDictionary(
        x => x.Name.LocalName,
        x => x.Elements("Lookup")
              .Select(l => new KeyValuePair<string, string>(
                   (string) l.Attribute("Key"),
                   (string) l.Attribute("Replace"))
              .ToList()
    );

然后在ReferenceLists中查找Replacement.Reference以获得键/值对列表。

像这样?https://forums.asp.net/t/1964585.aspx?how + + +阅读+ xml元素中使用+ linq + + + c +网络+递归+

必须改进,但是:

 string strFilename = "/Message.xml";
            strFilename = Server.MapPath(strFilename);
            XmlDocument xmlDoc = new XmlDocument();
            if (File.Exists(strFilename))
            {
                XmlTextReader rdrXml = new XmlTextReader(strFilename);
                do
                {
                    switch (rdrXml.NodeType)
                    {
                        case XmlNodeType.Text:
                            //Console.WriteLine("{0}", rdrXml.Value);
                            Response.Write(rdrXml.Value + "<br/>");
                            break;
                    }
                } while (rdrXml.Read());
            }

下面是一个解析xml字符串并递归打印属性名称和值的通用程序。我希望你能根据你的要求检查一下这个名字是否是一个参考值,然后从那里开始。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication9
{
  class Program
  {
    static void Main(string[] args)
    {
        string xmlstring = @"<MapFile>
                                 <Import>
                                  <field name1=""BorrowId"" name2=""EMPLID"" />
                                  <field name1=""Firstname"" name2=""COMPLETENAME"" />
                                  <field name1=""Address"" name2=""Address"" Reference=""Location"" />
                                 </Import>
                                 <Location>
                                  <Lookup Key=""CC"" Replace=""1"" />
                                  <Lookup Key=""CE"" Replace=""2"" />
                                 </Location>
                                </MapFile>";
        XElement xmlTree = XElement.Parse(xmlstring);
        ParseChildElement(xmlTree);
        Console.ReadLine();
    }
    static void ParseChildElement(XElement xmlTree)
    {
        PrintAttributes(xmlTree);
        foreach(XElement element in xmlTree.Elements())
        {
            ParseChildElement(element);
        }
    }
    static void PrintAttributes(XElement xmlTree)
    {
        foreach (XAttribute attr in xmlTree.Attributes())
        {
            string[] attribArray = attr.ToString().Split('=');
            if (attribArray.Length > 1)
                Console.WriteLine(string.Format(@" {0} = {1}", attr.Name, attr.Value));
        }
    }
}

}