仅读取XML节点

本文关键字:节点 XML 读取 | 更新日期: 2023-09-27 18:10:12

我在获取XML的值时遇到了一个问题,当我调试时,它正在XML文档中加载它,但它没有找到我想要访问的值或节点。这是xml文件。我想要获取的值是"Active"。现在这个XML不是一个文件或任何东西,是作为一个字符串传递…(不能修改这部分)只能访问类,我可以创建函数来访问它,但不能修改实际代码获取值并将其作为"xml字符串"传递

<Clients>
  <BillingCycle>30</BillingCycle>
  <Category>1</Category>
  <Type>Admin</Type>
  <AddressCat>3</AddressCat>
  <ZipCodeCat>5</ZipCodeCat>
  <ClientManager>
    <UserID>5</UserID>
    <ZPVal>1</ZPVal>
    <DRY1>Test</DRY1>
    <Active>1</Active>
  </ClientManager>
</Clients>

这里的c#代码

public bool IsActive(int ClientID, int VassID)
        {
            bool isActive = false;
            HelperClass helper = new HelperClass();
            XmlDocument xml = new XmlDocument();
            //at this point i can see the data was stored in the xml when debugging
            xml.LoadXml(helper.GetClientXML(ClientID, VassID));
           //have tried the following do not woerk
         //   XmlNode node = xml.SelectSingleNode ("/Clients/ClientManager/Active/text()");
            XmlNode node = xml.SelectSingleNode("Clients/ClientManager/Active");
            int isActiveVal = Convert.ToInt32(node.Value);
            if (isActiveVal == 1)
            {
                isActive = true;
            }
            return isActive;
        }

仅读取XML节点

这行可以:

//XmlNode node = xml.SelectSingleNode ("/Clients/ClientManager/Active/text()");
var activeTextNodes = xml.SelectNodes("/Clients/ClientManager/Active/text()");

…但是它会选择一组Active text()值,这是您可能不想要的。

您可以访问您找到的节点的InnerText值:

XmlNode node = xml.SelectSingleNode("Clients/ClientManager/Active");
int isActiveVal = Convert.ToInt32(node.InnerText);

或者您可以访问First Child的值:

XmlNode node = xml.SelectSingleNode("Clients/ClientManager/Active");
int isActiveVal = Convert.ToInt32(node.FirstChild.Value);

以上所述,您应该使用int.TryParse而不是Convert.ToInt32,因为它不会对非整数数据抛出异常。

使用InnerText代替Value