0

您好,我的 xml 具有相同的嵌套元素。它是递归的(快乐!)

像这样:

<MyRoot>
  <Record Name="Header" >
    <Field Type="Pattern" Expression=";VR_PANEL_ID,\s+" />
    <Field Name="PanelID" Type="Pattern" Expression="\d+"/>
    <Field Type="Pattern" Expression="," />
    <Field Name="ProductionDateTime" Type="Pattern" Expression=".+?(?=,)" />
    <Field Type="Pattern" Expression=".+?" />
  </Record>
  <Record Name="Body" MaxOccurs="0">
    <Record Name="Command"  Compositor="Choice">
      <Record Name="Liquid Status" >
        <Record Name="Header" >
          <Field Type="Pattern" Expression="i30100" />
          <Field  Name="DateTime" Type="Pattern" Expression="\d{10}"/>
        </Record>
        <Record Name="Data" MinOccurs="0" MaxOccurs="0">
          <Field Name="DeviceNum" Type="Pattern" Expression="\d\d" />
          <Field Name="Status" Type="Pattern" Expression="\d{4}" />
        </Record>
      </Record>
    </Record>
    <Record Name="Footer" >
      <Field Type="Pattern" Expression="&amp;&amp;[A-F0-9]" />
    </Record>
  </Record>
</MyRoot>

一旦XmlReader定位在 上MyRoot,我怎么能只循环通过MyRoot(在这种情况下,<Record Name="Header" ><Record Name="Body" MaxOccurs="0">)的直接子级。我正在以递归方式将这些节点的 xml 读取委托给另一个类。

在考虑重复的问题之前,请确保 OP 没有询问孙子或其他一些节点集,除了 xpath 的 xpath 轴children。我找不到这个问题的完全匹配,而且XmlReader似乎一直想先深入。

我想做的是交出XmlReader并让正在使用子 xml 的子对象将它交还给我,指向它需要获取下一个孩子的位置。那会很甜蜜。

4

1 回答 1

0

这是有效的。抱歉,它不是 100% 通用的,但它可能会给你一个想法:

public void ReadXml(System.Xml.XmlReader reader)
{
    ReadAttributes(this, reader);
    reader.Read(); //advance
    switch (reader.Name) {
        case "Record":
        case "Field":
            break;
        default:
            reader.MoveToContent(); //skip other nodes
            break;
    }

    if (reader.Name == "Record") {
        do {
            LexicalRecordType Record = new LexicalRecordType();
            Record.ReadXml(reader);
            Records.Add(Record);
            //.Read() 
        } while (reader.ReadToNextSibling("Record")); //get next record
    } else if (reader.Name == "Field") {
        do {
            LexicalField Field = Deserialize(reader.ReadOuterXml, typeof(LexicalField));
            Add(Field);
        } while (reader.Name == "Field");
    }
}

public void ReadAttributes(object NonSerializableObject, System.Xml.XmlReader XmlReader)
{
    XmlReader.MoveToContent();
    for (int Index = 0; Index <= XmlReader.AttributeCount - 1; Index++) {
        XmlReader.MoveToAttribute(Index);
        PropertyInfo PropertyInfo = NonSerializableObject.GetType.GetProperty(XmlReader.LocalName);
        PropertyInfo.SetValue(NonSerializableObject, ConvertAttribute(XmlReader.Value, PropertyInfo.PropertyType), null);
    }
    XmlReader.MoveToContent();
}
于 2015-02-18T17:20:43.763 回答