Skip to main content
 首页 » 编程设计

c#之如何读取 XML 文件节点属性和子节点属性值

2024年02月20日12落叶无声

如何读取包含以下内容的 xml 文件:

<?xml version="1.0" encoding="utf-8"?> 
<A> 
   <B value="1"> 
     <Hash algo="SHA256" value="905C45B51B970434D7159641D9F6A88DC91E9C35030618A729C8E4BE174711AF" /> 
   </B> 
   <B value="2"> 
     <Hash algo="SHA256" value="649721FF455E9B100E691A3857696350E14364029C34C9438AB3EA9665C91292" /> 
   </B> 
   <B value="3"> 
     <Hash algo="SHA256" value="90FC91C4B82BF440FDAFECF3303DCA8FB9F2E9D7EFFAE394D8B74D0C7CD7DA10" /> 
   </B> 
</A> 

在上面的 xml 文件中,我想读取所有 B 标签的“value”属性值和标签 Hash 的“algorithm”或“value”属性值.

这是我使用的代码:

        var settings = new XmlReaderSettings(); 
        settings.IgnoreWhitespace = true; 
        using (var stm = new FileStream(@"xmlFilePath", FileMode.Open, FileAccess.Read, FileShare.Read)) 
        using (var reader = XmlReader.Create(stm, settings)) 
        { 
            while (reader.Read()) 
            { 
                string srcFileHash=null; 
                reader.ReadToDescendant("B"); 
                if (reader.NodeType == XmlNodeType.Element && reader.LocalName == "B") 
                { 
                    reader.MoveToAttribute("value"); 
                    var bValue=reader.Value;   // get the B tag attribute value. 
 
                    //also want to read the <hash value=? and algo=?. but I dnt know how to get these hash tag attributes. 
                } 
            } 
        } 

请您参考如下方法:

XDocument xDoc = XDocument.Parse(xml); 
var result = xDoc.Descendants("B") 
    .Select(b => new 
    { 
        BValue = b.Attribute("value").Value, 
        Alg = b.Element("Hash").Attribute("algo").Value, 
        AlgValue = b.Element("Hash").Attribute("value").Value, 
    }) 
    .ToArray();