请帮我读一下xml并将其存储在一个字符串中 [英] Please help me to read the xml and store it in a string
本文介绍了请帮我读一下xml并将其存储在一个字符串中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想读取x,y,角度,方向,文件的值
I want to read the values of x,y,angle,direction,file
<DESCIONTREE>
<Motion X="296" Y="88" Angle="-90" Direction="up" file="2.jpg" />
<Motion X="384" Y="94" Angle="90" Direction="down" file="2.jpg" />
<Motion X="480" Y="94" Angle="90" Direction="down" file="2.jpg" />
<Motion X="272" Y="106" Angle="90" Direction="down" file="2.jpg" />
</DESCIONTREE>
string contents = File.ReadAllText("test.xml");
XmlDocument xml = new XmlDocument();
xml.LoadXml(contents); // suppose that str string contains "<Names>...</Names>"
XmlNodeList xnList = xml.SelectNodes("/DESCIONTREE/Motion");
foreach (XmlNode xn in xnList)
{
// Console.WriteLine(xn.InnerText);
richTextBox1.AppendText(xn.OuterXml+ "\n");
}
但我想存储每个变量
but i want to store each variable
String x,y,angle,direction,file ;
推荐答案
您可以直接访问这些属性:
You can access the attributes directly:
XmlDocument xml = new XmlDocument();
xml.LoadXml(@"
<DESCIONTREE>
<Motion X='296' Y='88' Angle='-90' Direction='up' file='2.jpg' />
<Motion X='384' Y='94' Angle='90' Direction='down' file='2.jpg' />
</DESCIONTREE>
");
XmlNodeList xnList = xml.SelectNodes("/DESCIONTREE/Motion");
foreach (XmlNode xn in xnList)
{
Console.WriteLine("{0} {1} {2} {3} {4}", xn.Attributes["X"].Value, xn.Attributes["Y"].Value, xn.Attributes["Angle"].Value, xn.Attributes["Direction"].Value, xn.Attributes["file"].Value);
}
但我建议您声明一个类,然后使用反序列化。请看这里: http://undefinedvalue.com/2011/11/22/deserializing-objects-xml -c [ ^ ]
您好,
您已经阅读了以下属性:
foreach(xnList中的xmlNode xn)
{
string attributeValue = xn.Attributes [X ]。值; //得到X值。
}
希望这可以解决你的问题。
问候
Hi,
you have read the attributes which you can achieve by following:
foreach (XmlNode xn in xnList)
{
string attributeValue = xn.Attributes["X"].Value; // to get the X value.
}
Hope this can solve your problem.
Regards
Hello Vishnulalr,
以下代码片段演示如何从节点读取单个属性值。
Hello Vishnulalr,
Following code snippet demonstrate how you can read individual attribute values from node.
using System;
using System.Xml;
class XMLTest {
public static void Main() {
XmlDocument xdoc = new XmlDocument();
xdoc.Load("G:\\text.xml");
XmlNodeList xnLst = xdoc.SelectNodes("/DESCIONTREE/Motion");
foreach (XmlNode node in xnLst) {
Console.WriteLine(node.Attributes.GetNamedItem("X").Value);
Console.WriteLine(node.Attributes.GetNamedItem("Y").Value);
Console.WriteLine(node.Attributes.GetNamedItem("Angle").Value);
Console.WriteLine(node.Attributes.GetNamedItem("Direction").Value);
Console.WriteLine(node.Attributes.GetNamedItem("file").Value);
Console.WriteLine("");
}
Console.ReadKey();
}
}
问候,
Regards,
这篇关于请帮我读一下xml并将其存储在一个字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文