在XML處理中,StringReader類可以用來讀取XML字符串并將其轉換為XML節點或文檔對象,以便進行進一步的處理和操作。以下是StringReader類在XML處理中的一些常見應用:
string xmlString = "<root><child>value</child></root>";
XmlDocument doc = new XmlDocument();
using (StringReader stringReader = new StringReader(xmlString))
{
using (XmlReader xmlReader = XmlReader.Create(stringReader))
{
doc.Load(xmlReader);
}
}
string xmlString = "<root><child attribute='value'>content</child></root>";
using (StringReader stringReader = new StringReader(xmlString))
{
using (XmlReader xmlReader = XmlReader.Create(stringReader))
{
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
if (xmlReader.HasAttributes)
{
string attributeValue = xmlReader.GetAttribute("attribute");
Console.WriteLine(attributeValue);
}
}
else if (xmlReader.NodeType == XmlNodeType.Text)
{
string nodeValue = xmlReader.Value;
Console.WriteLine(nodeValue);
}
}
}
}
string xmlString = "<root><child attribute='value'>content</child></root>";
using (StringReader stringReader = new StringReader(xmlString))
{
using (XmlReader xmlReader = XmlReader.Create(stringReader))
{
XPathDocument xpathDoc = new XPathDocument(xmlReader);
XPathNavigator navigator = xpathDoc.CreateNavigator();
XPathNodeIterator iterator = navigator.Select("//child");
while (iterator.MoveNext())
{
string nodeValue = iterator.Current.Value;
Console.WriteLine(nodeValue);
}
}
}
總的來說,StringReader類在XML處理中可以幫助我們方便地將XML字符串轉換為XML節點或文檔對象,并進行各種操作和查詢。