C#将XML划分为多个部分

时间:2016-06-14 08:14:38

标签: c# xml winforms

我正在尝试将XML文件分成几部分 我有一个像这样的XML文件

<?xml version="1.0" encoding="utf-8"?>
<RegistrationOpenData xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://example.gov">
<Description>Registration data is collected by ABC XYZ</Description>
<InformationURL>http://www.example.com/html/hpd/property-reg-unit.shtml</InformationURL>
<SourceAgency>ABC Department of Housing</SourceAgency>
<SourceSystem>PREMISYS</SourceSystem>
<StartDate>2016-02-29T00:03:06.642772-05:00</StartDate>
<EndDate i:nil="true" />
<Registrations>
<Registration xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<RegistrationID>1</RegistrationID>
<BuildingID>1A</BuildingID>
<element1>E11</element1>
<element2>E21</element2>
<element3>E31</element3>
<element4>E41</element4>
</Registration>
<Registration xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<RegistrationID>2</RegistrationID>
<BuildingID>2A</BuildingID>
<element1>E21</element1>
<element2>E22</element2>
<element3>E32</element3>
<element4>E42</element4>
</Registration>
</Registrations>
</RegistrationOpenData>

我正在尝试通过此代码获取节点数

XmlDocument doc = null;
doc = new XmlDocument();
doc.Load(@"D:\Registrations20160229.xml");
XmlNodeReader nodeReader = new XmlNodeReader(doc);
XmlElement root = doc.DocumentElement;
XmlNodeList elemList = root.GetElementsByTagName("Registration");
int totalnode = elemList.Count;
int nodehalf = totalnode / 2;
MessageBox.Show(nodehalf.ToString());

但在此之后我无法继续,这段代码我用来计算注册节点的数量然后把它们变成一半,现在我不知道如何进一步分割这个文件,我总共有158718文件中的条目(注册节点)(有时甚至更多),我试图将所有部分分成几部分,可能是3到4部分。

1 个答案:

答案 0 :(得分:0)

试试这个,它不应该将整个xml加载到内存

        using(XmlReader reader = XmlReader.Create(new FileStream(@"D:\Registrations20160229.xml" , FileMode.Open))){
                        while (reader.Read())
        {
            if(reader.NodeType == XmlNodeType.Element && reader.Name == "Registration")
                counter++;
        }
        Console.WriteLine(counter);
        }