【问题标题】:XmlReader - read childXmlReader - 读取孩子
【发布时间】:2015-12-21 09:59:15
【问题描述】:

我在使用 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 的元素“单位”?

其实我试过把这个字符串解析成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>

【问题讨论】:

  • 如果这是一个 C# 问题,那么请展示您的代码并解释您的“问题”到底是什么。
  • 你试过什么?你期望输出是什么?对这么小的 XML 文档使用如此低级的 API 的原因是什么? LINQ to XML 将使这变得微不足道。
  • 我更新了帖子。我想只读“单位”元素,它是数据的直接子元素

标签: c# xml xmlreader


【解决方案1】:

请参阅下面的示例,了解如何使用 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();
                }
            }
        }
    }

【讨论】:

    【解决方案2】:

    XPathReader 可以帮助您。在这里你可以找到全文:https://msdn.microsoft.com/en-us/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);
          }
       }  
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多