请帮助,我有xml文件,
<Users>
<User FullName="" Name="sa">
<userAvatarCache>-1</userAvatarCache>
<description></description>
<email></email>
<phone></phone>
<UserActive>true</UserActive>
</User>
<User FullName="asfgd" Name="stest">
<userAvatarCache>-1</userAvatarCache>
<description>aasad</description>
<email>test@ukr.net</email>
<phone>sdafdsfds0850</phone>
<UserActive>true</UserActive>
</User>
</Users>
我需要通过电子邮件选择 FullName 。 我使用
获得了所有结构 XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(res.GetResponseStream());
XmlNode xmlNode = xmlDoc.DocumentElement.SelectSingleNode("User");
现在我只需要通过电子邮件发送1个结果(全名)。 我怎么能做对吗? 感谢
答案 0 :(得分:3)
请google XPath,然后尝试使用它。请注意,对大文件使用XmlDocument是一个非常糟糕的主意。
代码:
var rawXml = @"<Users>
<User FullName="""" Name=""sa"">
<userAvatarCache>-1</userAvatarCache>
<description></description>
<email></email>
<phone></phone>
<UserActive>true</UserActive>
</User>
<User FullName=""asfgd"" Name=""stest"">
<userAvatarCache>-1</userAvatarCache>
<description>aasad</description>
<email>test@ukr.net</email>
<phone>sdafdsfds0850</phone>
<UserActive>true</UserActive>
</User>
</Users>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(rawXml);
string email = "test@ukr.net";
string selector = string.Format("User[email=\"{0}\"]", email);
XmlNode xmlNode = xmlDoc.DocumentElement.SelectSingleNode(selector);
if(xmlNode != null)
{
string fullName = xmlNode.Attributes["FullName"].Value;
Console.WriteLine(fullName);
}
答案 1 :(得分:1)
XPath to select element based on childs child value非常清楚。
string xmlString = @"
<Users>
<User FullName='' Name='sa'>
<userAvatarCache>-1</userAvatarCache>
<description></description>
<email></email>
<phone></phone>
<UserActive>true</UserActive>
</User>
<User FullName='asfgd' Name='stest'>
<userAvatarCache>-1</userAvatarCache>
<description>aasad</description>
<email>test@ukr.net</email>
<phone>sdafdsfds0850</phone>
<UserActive>true</UserActive>
</User>
</Users>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);
XmlNode xmlNode = xmlDoc.DocumentElement.SelectSingleNode("./User[email = 'test@ukr.net']");