字符串C#的xml值
问题描述:
使用a:
Using a:
WebBrowser web = new WebBrowser();
我去了这个网站:`` http://www.ctt.pt/pdcp/xml_pdcp ''
我想将值放入字符串中...
你能帮我吗?
问候,
KZ
I go to this website: ''http://www.ctt.pt/pdcp/xml_pdcp''
and I want to get the values into strings...
Can you help me?
Regards,
KZ
答
XmlDocument xml = new XmlDocument();
xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>"
XmlNodeList xnList = xml.SelectNodes("/Names/Name");
foreach (XmlNode xn in xnList)
{
string firstName = xn["FirstName"].InnerText;
string lastName = xn["LastName"].InnerText;
Console.WriteLine("Name: {0} {1}", firstName, lastName);
}
可以使用XElement
和LINQ
创建值的dictionary
,其中元素的名称是键,而元素的值是对应于键的值,如下所示:
Adictionary
of values can be created usingXElement
andLINQ
, where the name of the element is the key and the value of element is the value corresponding to the key as shown below:
string xmlData = @"<Erro total=""0"" razao=""PEIN"" inicio=""0"" fim=""0"">
<Criterio>
<inDistrito/>
<inConcelho/>
<inLocal/>
<inRua/>
<inPorta/>
<inCodPos/>
<inCliente/>
<inIdLocal/>
<inIdRua/>
<inEp/>
<inApartado/>
<inIdEp/>
<inPag>1</inPag>
<inMaxPag>20</inMaxPag>
<Id_Pesq>68083086</Id_Pesq>
</Criterio>
</Erro>";
XElement element = XElement.Parse(xmlData);
Dictionary<string,object> values = new Dictionary<string,object>();
element.Element("Criterio").Elements()
.Select (e => {
values.Add(e.Name.ToString(),e.Value);
return e;
}).Count ();
//[Edit] Modified as pointed out by Losmac [/Edit]
XElement element = XElement.Parse(xmlData);
List<KeyValuePair<string,object>> values = element.Element("Criterio").Elements()
.Select (e => new KeyValuePair<string,object>(
e.Name.ToString(),e.Value)
).ToList();
//values
//Key Value
//inDistrito
//inConcelho
//inLocal
//inRua
//inPorta
//inCodPos
//inCliente
//inIdLocal
//inIdRua
//inEp
//inApartado
//inIdEp
//inPag 1
//inMaxPag 20
//Id_Pesq 68083086
DataSet ds = new DataSet("Whatev");
System.IO.TextReader txtReader = new System.IO.StringReader(XmlString);
System.Xml.XmlReader reader = new System.Xml.XmlTextReader(txtReader);
ds.ReadXml(reader);
foreach (System.Data.DataRow DrW in ds.Tables[0].Rows)
{
foreach (System.Data.DataColumn DC in DrW.Table.Columns)
{
Console.Write(DC.ColumnName + "=" + DC.ToString());
}
}