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

时间:2016-10-24 06:41:59

标签: c# xml linq

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

3 个答案:

答案 0 :(得分:1)

好的,所以看起来你想要这样的东西,它会加载field刚根 - 根元素中的所有Import元素,然后通过查找每个元素来加载参考列表< em>不是 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()
    );

然后,您可以在Replacement.Reference中查找ReferenceLists以获取键/值对列表。

答案 1 :(得分:0)

这样的东西? 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());
            }

答案 2 :(得分:0)

以下是一个通用程序,它解析xml字符串并递归打印属性名称和值。我希望您可以根据您的要求检查名称是否为参考值,并从那里开始..

// enables SMTP debug information (for testing)
$mail->SMTPDebug  = 1;  // 1 = errors and messages
OR
$mail->SMTPDebug  = 2; // 2 = messages only

//Send email
if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

}