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

C# 使用Linq to XML从XML文件中按属性名称获取所有属性值,c#,xml,linq,C#,Xml,Linq,我有一个XML文件,我必须从XML中提取所有属性值。我已经尝试了下面的一个,但我需要它在林克。谁能指导我怎么做 示例XML <MapFile> <Import> <field name1="BorrowId" name2="EMPLID" /> <field name1="Firstname" name2="COMPLETENAME" /> <field name1="Address" name2="Address" Refer

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

示例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>
代码

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);
}
XmlDocument xmlDoc=new XmlDocument();
xmlDoc.Load(@sPath);
var attrValues=xmlDoc.GetElementsByTagName(“字段”);
List MapFileMod=新列表();
foreach(属性值中的xmlnodex)
{
MapFileModel_objMapFile=新的MapFileModel();
如果(x.Attributes[“name1”!=null)
{
_objMapFile.CurrentVal=x.Attributes[“name1”]!=null?x.Attributes[“name2”]。值:null;
_objMapFile.NewVal=x.Attributes[“name2”]!=null?x.Attributes[“name2”]。值:null;
_objMapFile.Reference=x.Attributes[“Reference”!=null?x.Attributes[“Reference”]。值:null;
}
MapFileMod.Add(_objMapFile);
}
像这样的东西?

必须改进,但:

 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());
            }
string strFilename=“/Message.xml”;
strFilename=Server.MapPath(strFilename);
XmlDocument xmlDoc=新的XmlDocument();
if(File.Exists(strFilename))
{
XmlTextReader rdrXml=新的XmlTextReader(strFilename);
做
{
开关(rdrXml.NodeType)
{
案例XmlNodeType.Text:
//WriteLine(“{0}”,rdrXml.Value);
Write(rdrXml.Value+“
”); 打破 } }while(rdrXml.Read()); }
好的,看起来您想要这样的东西,它加载根元素下方的
导入
中的所有
字段
元素,然后通过查找每个非
导入
的元素来加载引用列表

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()
    );
var doc=XDocument.Load(“foo.xml”);
var替换=单据
.根
.要素(“进口”)
.要素(“字段”)
.选择(x=>新替换{
CurrentValue=(字符串)x.Attribute(“名称1”),
NewValue=(字符串)x.Attribute(“name2”),
Reference=(字符串)x.Attribute(“Reference”)
})
.ToList();
var referenceLists=doc
.根
.要素()
.Where(f=>f.Name.LocalName!=“导入”)
.ToDictionary(
x=>x.Name.LocalName,
x=>x.Elements(“查找”)
.选择(l=>new KeyValuePair(
(字符串)l.属性(“键”),
(字符串)l.Attribute(“替换”))
托利斯先生()
);

然后在
ReferenceLists
中查找
替换项。Reference
以获得键/值对列表。

下面是一个通用程序,它解析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));
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Xml.Linq;
使用系统文本;
使用System.Threading.Tasks;
命名空间控制台应用程序9
{
班级计划
{
静态void Main(字符串[]参数)
{
字符串xmlstring=@”
";
XElement xmlTree=XElement.Parse(xmlstring);
ParseChildElement(xmlTree);
Console.ReadLine();
}
静态void ParseChildElement(XElement xmlTree)
{
printtributes(xmlTree);
foreach(xmlTree.Elements()中的XElement元素)
{
元素(element);
}
}
静态void打印属性(XElement xmlTree)
{
foreach(xmlTree.Attributes()中的XAttribute attr)
{
字符串[]attribArray=attr.ToString().Split('=');
如果(attribArray.Length>1)
WriteLine(string.Format(@“{0}={1}”,attr.Name,attr.Value));
}
}
}

}

首先,我要使用LINQ to XML,这是一种比
XmlDocument
更干净的API,而且对LINQ更友好。现在,从您的代码来看,您的要求似乎比“我必须提取所有属性值”更高-请在您的问题中表达这些。目前还不清楚您到底想要什么。对不起,除了提取属性值的数量,我没有看到任何其他要求。那么为什么您的代码中有所有这些字符串文本来查找特定属性?只是提取“所有属性值”简单到
doc.subjects().SelectMany(x=>x.Attributes().Select(a=>a.Value))
。但我想这不是您想要的-这只会给您一个
IEnumerable
,一个所有属性值的序列。如果您提供一个简短的XML示例文档和预期的输出,这会有所帮助…请参阅我更新的问题和详细信息。关于示例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));
        }
    }
}