XmlReader - 只能读取“子xpath轴”
问题描述:
你好我有xml嵌套元素是相同的。它是递归(快乐!)XmlReader - 只能读取“子xpath轴”
像这样:
<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="&&[A-F0-9]" />
</Record>
</Record>
</MyRoot>
一旦XmlReader
定位在MyRoot
,哪能只是环通只是MyRoot
直接孩子(在这种情况下,<Record Name="Header" >
和<Record Name="Body" MaxOccurs="0">
)。我将这些节点的xml委托给另一个类递归地读取。
在考虑重复问题之前,请确保OP没有询问除了xpath轴children
以外的其他节点集。我找不到这个问题的完全匹配,并且XmlReader
似乎想要始终保持深入。
我想做的事情是交出XmlReader
,并让孩子的对象消耗孩子的xml手把它带回我指向需要的地方,以获得下一个孩子。这将是甜蜜的。
答
这是什么工作。对不起,这不是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();
}
你是否限制使用'XmlReader'? – VMAtm 2015-02-17 20:39:03
@VMAtm,我正在实现'IXmlSerializable' – toddmo 2015-02-17 20:43:19