我搜索了几天如何解析我的xml文件。 所以我的问题是我想要恢复根元素的所有键值。
文件的例子:
<?xml version="1.0" ?>
<!DOCTYPE ....... SYSTEM ".....................">
<coverage x="y1" x2="y2" x3="y3" x4="y4">
<sources>
<source>.............</source>
</sources>
.....
<\coverage>
在这里,我想要恢复&#34;覆盖的所有价值&#34; :x1和他的值,x2和他的值,x3和他的值x3 ...... 我已经尝试过使用&#34; XmlReader&#34;我可以找到所有教程,但它仍然无法正常工作。 我尝试过的所有教程都可以尝试恢复某个节点(标记)中的值,但不会恢复根元素的所有值。
也许有同样问题的教程已经存在,但我还没有找到他。
提前感谢您的帮助。
答案 0 :(得分: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
答案 1 :(得分:0)
//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;
希望这有帮助。