通过 XmlDocument 按子节点选择父节点
本文关键字:选择 父节点 子节点 XmlDocument 通过 | 更新日期: 2023-09-27 18:34:03
请帮忙,我有 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>
我需要通过电子邮件选择全名。我得到了所有结构
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(res.GetResponseStream());
XmlNode xmlNode = xmlDoc.DocumentElement.SelectSingleNode("User");
现在我只需要通过电子邮件发送 1 个结果(全名)。我怎样才能正确做?谢谢
请谷歌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);
}
XPath 根据子值选择元素很好地涵盖了这一点。
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']");