我有以下XML:
<Run id="1">
<Servers>
<Server id="1" fqdn="ENG-HSINGH">
<Roles>
<Role id="1" rootFolder="C:\DeleteMe"/>
</Roles>
</Server>
</Servers>
<Roles>
<Role id="1">
<ValidationInformation>
<ValidationObject>
<FileSystem>
<Directory path="\A\HTML">
<File id="1" path="\A\HTML\1.HTM"/>
<File id="2" path="\A\HTML\2.ASP" />
</Directory>
<Directory path="\B\EntireFolder">
<File id="8" path="\B\EntireFolder\1.txt"/>
<File id="9" path="\B\EntireFolder\2.txt"/>
<File id="10" path="\B\EntireFolder\3.txt"/>
<File id="11" path="\B\EntireFolder\4.txt"/>
<File id="12" path="\EHR\EntireFolder\5.txt"/>
</Directory>
<Files>
<File id="4" path="\C\6.txt"/>
</Files>
</FileSystem>
</ValidationObject>
</ValidationInformation>
</Role>
<Role id="2">
<ValidationInformation>
<ValidationObject>
<FileSystem>
<Directory path="\D\HTML">
<File id="13" path="\D\HTML\1.HTM"/>
</Directory>
<Directory path="\E">
<File id="14" path="\E\1.txt"/>
</Directory>
<Files>
<File id="15" path="\F\1.txt"/>
</Files>
</FileSystem>
</ValidationObject>
</ValidationInformation>
</Role>
</Roles>
</Run>
我想将这个XML读入代表Roles的字典中,并将它作为string.e.g对应的ValidationInformation子XML。
1, "<ValidationObject><FileSystem><Directory path='\A\HTML'><File id='1' path='\A\HTML\1.HTM'/><File id='2' path='\A\HTML\2.ASP' /></Directory><Directory path='\B\EntireFolder'><File id='8' path='\B\EntireFolder\1.txt'/><File id='9' path='\B\EntireFolder\2.txt'/><File id='10' path='\B\EntireFolder\3.txt'/><File id='11' path='\B\EntireFolder\4.txt'/><File id='12' path='\EHR\EntireFolder\5.txt'/></Directory><Files><File id='4' path='\C\6.txt'/></Files></FileSystem></ValidationObject>"
2, "<ValidationObject><FileSystem><Directory path='\D\HTML'><File id='13' path='\D\HTML\1.HTM'/></Directory><Directory path='\E'><File id='14' path='\E\1.txt'/></Directory><Files><File id='15' path='\F\1.txt'/></Files></FileSystem></ValidationObject>"
我知道我可以在ValidationInformation节点下为每个角色读取XML节点并粘贴结果XML,但这似乎不是一个好方法。
有更清洁的方法吗?
谢谢, ħ
答案 0 :(得分:1)
这对我有用:
Dictionary<int, string> myDictionary = new Dictionary<int, string>();
XmlDocument xml = new XmlDocument();
xml.LoadXml(<myInputXMLAsString>);
XmlNodeList xnList = xml.SelectNodes("/Run/Roles");
foreach (XmlNode xn in xnList)
{
int roleId = int.Parse(xn["Role"].Attributes["id"].Value);
XmlDocument subXmlDocument = new XmlDocument();
subXmlDocument.LoadXml(xn.InnerXml);
XmlNodeList subXn = subXmlDocument.SelectNodes("/Role/ValidationInformation");
string validationInfo = subXn[0].InnerXml;
roleIdToValidationInformationDictionary.Add(roleId, validationInfo);
}