[英]Pull specific xml tag in a xml file using XmlDocument
我有一個 xml 文件,我想要做的是解析完整的文件並搜索特定的 xml 標簽(在我的情況下我正在搜索queryString
),當遇到標簽時,拉出與其對應的內部文本。 我正在使用XmlDocument
並使用XmlDocument.SelectNodes("/stringList")
。
這樣做時會返回一個null
值。 我錯過了什么嗎?
XmlDocument xml = new XmlDocument();
Jrxml.Load(file_path);
XmlNodeList xml_nodes = xml.SelectNodes("/stringList");
foreach (XmlNode jr_node in xml_nodes)
{
XmlNode query_node = jr_node.SelectSingleNode("queryString");
}
執行時它不會進入 for 循環,因為xml_nodes
值為null
Xml 文件看起來像這樣。
<stringList>
<property1/>
<property2/>
<style>
<queryString>
</queryString>
</style>
<queryString>
</queryString>
</stringList>
如果您只搜索“queryString”標簽,我建議您使用 XmlDocument 方法 GetElementsByTagName。 考慮:
using System;
using System.Xml;
namespace TestCon
{
class Program
{
private static XmlDocument TestDoc;
public static void Main(string[] args)
{
TestDoc = new XmlDocument();
TestDoc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
"<stringList>\n"+
"<property1/>\n"+"<property2/>\n"+
"<style>\n"+"<queryString>Who's on fist."+"</queryString>\n"+
"</style>\n"+"<queryString>Who's on second."+"</queryString>\n"+
"</stringList>");
XmlNodeList elemList = TestDoc.GetElementsByTagName("queryString");
foreach (XmlNode foundNode in elemList)
{
Console.WriteLine(foundNode.InnerText);
}
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
您將獲得您正在搜索的兩個節點:
Who's on first.
Who's on second.
Press any key to continue . . .
我更喜歡System.Xml.Linq 中的 XML 類/功能:
XDocument doc = XDocument.Parse(xmlString);
foreach (XElement queryString in doc.Descendants("queryString"))
{
// do something with queryString.Value ...
}
你可以像這樣使用xml linq
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string xml =
"<root>" +
"<stringList>" +
"<property1/>" +
"<property2/>" +
"<style>" +
"<queryString>" +
"</queryString>" +
"</style>" +
"<queryString>" +
"</queryString>" +
"</stringList>" +
"</root>";
XDocument doc = XDocument.Parse(xml);
var stringList = doc.Descendants("stringList").Select(x => new
{
property1 = x.Element("property1"),
property2 = x.Element("property2"),
style = x.Element("style"),
queryString = x.Element("queryString")
});
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.