如何比较 xml 文件中的字符串?
comparing a string from an xml file how?
我是新手,对此很头疼,好吧
我得到了一个 XML 文件,例如:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<Client>
<add key="City" value="Amsterdam" />
<add key="Street" value="CoolSingel" />
<add key="PostalNr" value="1012AA" />
<add key="CountryCode" value="NL" />
我正在尝试读取和比较 XML 文件中的值
这样我也不会锁定文件,如下所示:
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
FileStream xmlFile = new FileStream("c:\clients.xml",FileMode.Open,FileAccess.Read, FileShare.Read);
xmlDoc.Load(xmlFile);
到目前为止还不错,但我无法真正阅读它
if (xmlDoc.GetElementsByTagName("CountryCode")[0].Attributes[0].Value=="NL") {// do stuff}
作为新手在这里尝试了其他一些东西,但它就是行不通不知道我在这里做错了什么,有没有人看到它?
您的代码无效,因为 CountryCode
不是 标签名称,它是 属性值 。
由于您是新手,请学习更新的 API XDocument
,以替换您使用旧的 API XmlDocument
的方法。例如:
FileStream xmlFile = new FileStream(@"c:\clients.xml",FileMode.Open,FileAccess.Read, FileShare.Read);
XDocument doc = XDocument.Load(xmlFile);
//get <add> element having specific key attribute value :
var countryCode = doc.Descendants("add")
.FirstOrDefault(o => (string)o.Attribute("key") == "CountryCode");
if(countryCode != null)
//print "NL"
Console.WriteLine(countryCode.Value);
我是新手,对此很头疼,好吧 我得到了一个 XML 文件,例如:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<Client>
<add key="City" value="Amsterdam" />
<add key="Street" value="CoolSingel" />
<add key="PostalNr" value="1012AA" />
<add key="CountryCode" value="NL" />
我正在尝试读取和比较 XML 文件中的值 这样我也不会锁定文件,如下所示:
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
FileStream xmlFile = new FileStream("c:\clients.xml",FileMode.Open,FileAccess.Read, FileShare.Read);
xmlDoc.Load(xmlFile);
到目前为止还不错,但我无法真正阅读它
if (xmlDoc.GetElementsByTagName("CountryCode")[0].Attributes[0].Value=="NL") {// do stuff}
作为新手在这里尝试了其他一些东西,但它就是行不通不知道我在这里做错了什么,有没有人看到它?
您的代码无效,因为 CountryCode
不是 标签名称,它是 属性值 。
由于您是新手,请学习更新的 API XDocument
,以替换您使用旧的 API XmlDocument
的方法。例如:
FileStream xmlFile = new FileStream(@"c:\clients.xml",FileMode.Open,FileAccess.Read, FileShare.Read);
XDocument doc = XDocument.Load(xmlFile);
//get <add> element having specific key attribute value :
var countryCode = doc.Descendants("add")
.FirstOrDefault(o => (string)o.Attribute("key") == "CountryCode");
if(countryCode != null)
//print "NL"
Console.WriteLine(countryCode.Value);