2016-10-24 56 views
-1

我有一個XML文件,我必須從XML中提取所有屬性值。我已經嘗試了下面的一個,但我需要Linq。任何人都可以指導我如何做到這一點。通過使用Linq到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> 

預期結果

[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); 
} 
+0

嗯,我會使用LINQ to XML,這是開始*多*比'XmlDocument'更清潔的API,以及更多的LINQ友好。現在,根據您的代碼判斷,您看起來比「我必須提取所有屬性值」要求更多 - 請在您的問題中表達這些要求。目前尚不清楚你現在要求的是什麼。 –

+0

對不起,我沒有看到任何其他要求提取屬性值的數量。 – DonMax

+0

那麼爲什麼你的代碼有所有這些字符串文字來尋找*特定*屬性?只需提取「所有屬性值」就像doc.Descendants()一樣簡單。SelectMany(x => x.Attributes()。Select(a => a.Value))''。但這不是你想要的,我懷疑 - 這隻會給你一個「IEnumerable 」,這是所有屬性值的序列。如果您提供一個簡短的示例XML文檔和預期的輸出,它將會有所幫助... –

回答

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

好了,所以它看起來像你想是這樣的,它加載所有在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() 
    ); 

你會再看看的Replacement.ReferenceReferenceLists拿到鍵/值對列表。

0

查看下面是一個通用的程序,它解析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)); 
     } 
    } 
} 

}