如何使用C#代碼測試節點是否包含特定的字符串或字符。如何測試節點是否包含特定的字符串或字符作爲其文本值?
例如:
<abc>
<foo>data testing</foo>
<foo>test data</foo>
<bar>data value</bar>
</abc>
現在我需要測試的特定節點的值具有字符串「測試」?
輸出將是「foo的[1]」
如何使用C#代碼測試節點是否包含特定的字符串或字符。如何測試節點是否包含特定的字符串或字符作爲其文本值?
例如:
<abc>
<foo>data testing</foo>
<foo>test data</foo>
<bar>data value</bar>
</abc>
現在我需要測試的特定節點的值具有字符串「測試」?
輸出將是「foo的[1]」
你也該到的XPath文檔,然後可以使用查詢:
var xPathDocument = new XPathDocument("myfile.xml");
var query = XPathExpression.Compile(@"/abc/foo[contains(text(),""testing"")]");
var navigator = xpathDocument.CreateNavigator();
var iterator = navigator.Select(query);
while(iterator.MoveNext())
{
Console.WriteLine(iterator.Current.Name);
Console.WriteLine(iterator.Current.Value);
}
這將確定是否有任何元素(不只是富)含有期望的值,並且將打印元件的名稱和它的整個值。你沒有指定確切的結果應該是什麼,但這應該讓你開始。如果從文件加載使用XElement.Load(filename)
。
var xml = XElement.Parse(@"<abc>
<foo>data testing</foo>
<foo>test data</foo>
<bar>data value</bar>
</abc>");
// or to load from a file use this
// var xml = XElement.Load("sample.xml");
var query = xml.Elements().Where(e => e.Value.Contains("testing"));
if (query.Any())
{
foreach (var item in query)
{
Console.WriteLine("{0}: {1}", item.Name, item.Value);
}
}
else
{
Console.WriteLine("Value not found!");
}
如何指定編寫XML的路徑,而不是XElement.Parse中的標籤。我需要加載名稱爲「sample.xml」的外部文件 – user268533 2010-04-01 14:15:22
@beginner我更新了代碼以顯示此內容(在xml下面註釋)。我在我的文章中提到可以使用'XElement.Load(「sample.xml」)'或者也可以使用'XDocument.Load(「sample.xml」)'但是如果你使用'XDocument',你會需要使用'xml.Root.Elements(...)'(注意''Root'屬性)。 – 2010-04-01 14:26:52
您可以使用LINQ到XML
string someXml = @"<abc>
<foo>data testing</foo>
<foo>test data</foo>
</abc>";
XDocument doc = XDocument.Parse(someXml);
bool containTesting = doc
.Descendants("abc")
.Descendants("foo")
.Where(i => i.Value.Contains("testing"))
.Count() >= 1;
如何使用代碼顯示節點的名稱和值?使用屬性名稱和值給出錯誤。 – user268533 2010-04-01 14:35:12
@beginner:我更新了我的答案,循環查看結果並打印出每個結果的名稱和值。 – 2010-04-01 14:45:47