繁体   English   中英

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

[英]Get all the attribute values by attribute name from XML file using Linq to XML

我有一个 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);
}

好的,所以看起来你想要这样的东西,它加载Import just-below-root 元素中的所有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+to+read+xml+elements+using+linq+in+c+net+recursively+

必须改进,但:

 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));
        }
    }
}

}

暂无
暂无

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

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