[英]XmlReader - read child
我在使用xmlReader讀取字符串(xml結構)時遇到麻煩。
string xml = @"
<Data>
<Prices Id="16" Code="C3" >
<Units>
<Unit Id="17"/>
</Units>
</Prices>
<Units>
<Unit Id="1" IsActive="true" />
<Unit Id="2" IsActive="true" />
</Units>
<Product Id="16" Code="C3" >
<Names>
<Name NameVersion="1" Name="C3 " />
</Names>
<Units>
<Unit Id="16"/>
</Units>
</Product>
</Data>
"
我怎樣才能只讀取孩子ID為1和2的元素“ Units”?
實際上,我嘗試將此字符串解析為XDocument。
var root = XElement.Parse(xmlFile);
var units = root.Elements("Units").FirstOrDefault();
並且它可以正常工作,但是我可以使用很大的xml,並且我不想將所有字符串解析為XDocument。 我正在尋找可以從字符串中部分加載元素的方法。 我也嘗試使用XmlTextReader做到這一點,但這在我的情況下不起作用
using (XmlReader xmlTextReader = XmlReader.Create(new StringReader(xmlFile)))
{
if (xmlTextReader.ReadToFollowing(elementName))
{
bool isOnNode = xmlTextReader.ReadToDescendant(elementName);
while (isOnNode)
{
yield return XNode.ReadFrom(xmlTextReader) as XElement;
if (!xmlTextReader.IsStartElement(elementName))
isOnNode = xmlTextReader.ReadToNextSibling(elementName);
}
}
}
預期輸出:xElement =
<Units>
<Unit Id="1" IsActive="true" />
<Unit Id="2" IsActive="true" />
</Units>
請參閱以下示例,了解如何使用XmlReader
解析xml的示例。 遍歷所有節點,直到找到一個Unit
元素。 然后,它檢查屬性值Id
的存在並解析IsActive
的值:
public static void Main()
{
string xml = "<Data><Units><Unit Id=\"1\" IsActive=\"true\" /><Unit Id=\"2\" IsActive=\"true\" /></Units><Product Id=\"16\" Code=\"C3\" ><Names><Name NameVersion=\"1\" Name=\"C3 \" /></Names><Units><Unit Id=\"16\"/></Units></Product></Data>";
var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
XmlTextReader reader = new XmlTextReader(memoryStream);
while (reader.Read())
{
//keep reading until we see a book element
if (reader.Name.Equals("Unit") &&
(reader.NodeType == XmlNodeType.Element))
{
if (reader.GetAttribute("Id") == "1" || reader.GetAttribute("Id") == "2")
{
string isActive = reader.GetAttribute("IsActive");
}
else
{
reader.Skip();
}
}
}
}
XPathReader可以為您提供幫助。 在這里您可以找到完整的文章: https : //msdn.microsoft.com/zh-cn/library/ms950778.aspx簡短示例:使用系統; 使用System.Xml; 使用System.Xml.XPath; 使用GotDotNet.XPath;
public class Test{
static void Main(string[] args) {
try{
XPathReader xpr = new XPathReader("books.xml", "//book/title");
while (xpr.ReadUntilMatch()) {
Console.WriteLine(xpr.ReadString());
}
Console.ReadLine();
}catch(XPathReaderException xpre){
Console.WriteLine("XPath Error: " + xpre);
}catch(XmlException xe){
Console.WriteLine("XML Parsing Error: " + xe);
}catch(IOException ioe){
Console.WriteLine("File I/O Error: " + ioe);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.