我有一个XML文件,我想从以下XML中brandname
brandcode
时检索001
。
<Root>
- <data>
<Companycode>TF</Companycode>
<Productcode>00001</Productcode>
<Productname>VPU</Productname>
<Brandcode>001</Brandcode>
<Brandname>DB</Brandname>
</data>
- <data>
<Companycode>TF</Companycode>
<Productcode>00002</Productcode>
<Productname>SENDERCARD</Productname>
<Brandcode>002</Brandcode>
<Brandname>LINSN</Brandname>
</data>
</Root>
这是我的代码;我需要在这里指定品牌名称:
XmlTextReader textReader = new XmlTextReader(@"codedata.xml");
textReader.Read();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(textReader);
XmlNodeList BCode = xmlDoc.GetElementsByTagName("Brandcode");
XmlNodeList BName = xmlDoc.GetElementsByTagName("Brandname");
for (int i = 0; i < BCode.Count; i++)
{
if (BCode[i].InnerText =="001")
{
string brandname = BName[i].InnerText;
}
//Console.WriteLine(BName[i].InnerText);
}
答案 0 :(得分:3)
以这种方式尝试......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace XmlReading
{
class Program
{
static void Main(string[] args)
{
//Create an instance of the XmlTextReader and call Read method to read the file
XmlTextReader textReader = new XmlTextReader("D:\\myxml.xml");
textReader.Read();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(textReader);
XmlNodeList BCode = xmlDoc.GetElementsByTagName("Brandcode");
XmlNodeList BName = xmlDoc.GetElementsByTagName("Brandname");
for (int i = 0; i < BCode.Count; i++)
{
if (BCode[i].InnerText == "001")
Console.WriteLine(BName[i].InnerText);
}
Console.ReadLine();
}
}
}
答案 1 :(得分:1)
试试这个XPath
://Brandname[../Brandcode[text()='001']]
使用XmlDocument.SelectSingleNode
:
var document = new XmlDocument();
var Brandcode = "001";
var xpath = String.Format(@"//Brandname[../Brandcode[text()='{0}']]",
Brandcode);
var Brandname = document.SelectSingleNode(xpath).InnerText;
并使用XDocument.XPathSelectElement
:
var document = XDocument.Load("fileName");
var name = document.XPathSelectElement(xpath).Value;
答案 2 :(得分:0)
你可以使用Xml.Linq命名空间,加载XDocument类并从xml文件中选择确切的元素:
XDocument doc = XDocument.Load(@"filePath");
var query = doc.Descendants("Root").Where(w => w.Element("Brandcode").Value == "001").Select(s => new { s.Element("Brandname").Value }).FirstOrDefault();
string brandname = query.Value;
答案 3 :(得分:0)
将品牌名称定义为字符串并为其指定null,然后在任何地方使用品牌名称....
namespace XmlReading
{
class Program
{
static void Main(string[] args)
{
//Create an instance of the XmlTextReader and call Read method to read the file
XmlTextReader textReader = new XmlTextReader("D:\\myxml.xml");
textReader.Read();
string brandname = null;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(textReader);
XmlNodeList BCode = xmlDoc.GetElementsByTagName("Brandcode");
XmlNodeList BName = xmlDoc.GetElementsByTagName("Brandname");
for (int i = 0; i < BCode.Count; i++)
{
if (BCode[i].InnerText == "001")
{
brandname = BName[i].InnerText;
}
}
Console.WriteLine(brandname);
Console.ReadLine();
}
}
}