【问题标题】:How to get all the key-values of the root element using c#?如何使用 c# 获取根元素的所有键值?
【发布时间】:2016-09-21 10:12:46
【问题描述】:

我搜索了几天如何解析我的 xml 文件。 所以我的问题是我想恢复根元素的所有键值。

文件示例:

<?xml version="1.0" ?>
<!DOCTYPE ....... SYSTEM ".....................">
<coverage x="y1"  x2="y2"  x3="y3"  x4="y4">
    <sources>
      <source>.............</source>
    </sources>
    .....
<\coverage>

在这里,我要恢复“覆盖”的所有值:x1 和他的值,x2 和他的值,x3 和他的值 x3... 我已经尝试在我能找到的所有教程中使用“XmlReader”,但它仍然不起作用。 我可以尝试的所有教程,恢复某个节点(标签)中的值,但从来没有恢复根元素的所有值。

也许已经存在有同样问题的教程,但我没有找到他。

提前感谢您的帮助。

【问题讨论】:

标签: c# xml-parsing xmlreader


【解决方案1】:

您可以使用XElement 来执行此操作。

XElement element = XElement.Parse(input);

var results = element.Attributes()
                     .Select(x=> 
                             new 
                             {
                                 Key = x.Name, 
                                 Value = (string)x.Value
                             });

输出

{ Key = x, Value = y1 }
{ Key = x2, Value = y2 }
{ Key = x3, Value = y3 }
{ Key = x4, Value = y4 }

查看Demo

【讨论】:

    【解决方案2】:
            //Use System.Xml namespace
            //Load the XML into an XmlDocument object
            XmlDocument xDoc = new XmlDocument();
            xDoc.Load(strPathToXmlFile); //Physical Path of the Xml File
            //or
            //xDoc.LoadXml(strXmlDataString); //Loading Xml data as a String
    
            //In your xml data - coverage is the root element (DocumentElement)
            XmlNode rootNode = xDoc.DocumentElement;
    
            //To get all the attributes and its values 
            //iterate thru the Attributes collection of the XmlNode object (rootNode)
            foreach (XmlAttribute attrib in rootNode.Attributes)
            {
                string attributeName = attrib.Name; //Name of the attribute - x1, x2, x3 ...
                string attributeValue = attrib.Value; //Value of the attribute
    
                //do your logic here 
            }
    
            //if you want to save the changes done to the document
            //xDoc.Save (strPathToXmlFile); //Pass the physical path of the xml file
    
            rootNode = null;
            xDoc = null;
    

    希望这会有所帮助。

    【讨论】:

    • 感谢您的回答,我想尝试您的代码,但我收到错误“(407)需要代理身份验证”),我认为(我什至很确定)这是因为我们有代理。所以,我将继续使用以前的解决方案,但无论如何感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多