如何将XML文档的值存储到c#中的字符串数组中? [英] How to store the values of an XML document into a string array in c#?
本文介绍了如何将XML文档的值存储到c#中的字符串数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个XML文档,其属性为IP,名称和值作为位置.我想先加载XML文档,然后提取名称为attribut的内容并将其存储在字符串数组中.
我可以通过
加载文档
Doc.Load("pathname");
但是如何检索值并将其存储在字符串数组中..
请使用您的代码帮助我
I have a XML document with attributes IP and Name and Value as Location. I want to load the XML document first and then extract the contents under name attribut and store it in a string array.
I can load the document by
Doc.Load("pathname");
but how to retrieve the values and store in a string array..
pls help me with ur code
推荐答案
Shaheen,
在下面的代码中,我使用了二维数组,并且可以使用
Shaheen,
In the below code I used a double dimensional array, and the name can be get by using
attributes.item[1].Value.ToString();
.
as you are using the XmlNode.Attributes property to get the attributes collection.
file.Load("C:\\Users\\shaheen.n\\Documents\\LocationFile.xml");
XmlNodeList tree = file.GetElementsByTagName("Mapping");
string[,] strarr = new string[tree.Count,3];
foreach (XmlNode node in tree)
{
XmlAttributeCollection attributes = node.Attributes;
ip = attributes.item[0].Value.ToString();
name = attributes.item[1].Value.ToString();
location = node.ChildNodes[0].Value.ToString();
// use the code to add to you string array, if you are using the double dimensional array, like -
strarr[ind,0] = ip;
strarr[ind,1] = name;
strarr[ind,2] = location;
ind++;
}
for(int i =0;i<strarr.length;i++)
{
if(strarr[0]==ip)
{
Console.WriteLine("LOCATION corresponding to the entered IP is : {0}",strarr[ind,2]);
Console.WriteLine("NAME corresponding to the entered IP is : {0}",strarr[ind,1]);
}
}
使用Linq转换为Xml(using System.Xlm.Linq;
).然后,您可以像这样进行整理(您可能需要对其进行一些微调,但是您明白了):
Use Linq to Xml (using System.Xlm.Linq;
). Then you can do somnething like this (you may need to tweak it a little, but you get the point):
XDocument = XDocument.Load(filename)
XElement root = xDocument.Element("IPLocation");
IEnumerable<XElement> list = root.Elements();
foreach (XElement element in list)
{
string ipAddr = element.Attribute("ip").Value;
string location = element.Element("Mapping").Value;
}
涉及的代码更少...
Much less code involved...
尝试一下-
Try this -
TextReader r = new StreamReader(pathname);
while ((i=r.ReadLine())!=null)
{
strXML += i;
}
这篇关于如何将XML文档的值存储到c#中的字符串数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文