XML节点始终为null

时间:2012-08-08 20:31:50

标签: c# xml xml-namespaces

以下函数不返回我想要的节点的值,即“CompanyPolicyId”。我尝试了很多东西,但仍然无法让它发挥作用。任何人都知道可能是什么问题?

 public void getpolicy(string rootURL, string policyNumber)
        {
            string basePolicyNumber = policyNumber.Remove(policyNumber.Length - 2);
            basePolicyNumber = basePolicyNumber + "00";

            using (WebClient client = new WebClient())
            {
                NetworkCredential credentials = new NetworkCredential();
                credentials.UserName = AppVars.Username;
                credentials.Password = AppVars.Password;
                client.Credentials = credentials;

                try
                {
                    XmlDocument doc = new XmlDocument();

                    doc.LoadXml(client.DownloadString(rootURL + basePolicyNumber));
                    XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable);
                    mgr.AddNamespace("zzzlocal", "http://com.zzz100.policy.data.local");

                    // Select the Identifier node with a 'name' attribute having an 'id' value
                    var node = doc.DocumentElement.SelectSingleNode("/InsurancePolicy/Indentifiers/Identifier[@name='CompanyPolicyId']", mgr);
                    if (node != null && node.Attributes["value"] != null)
                    {
                        // Pick out the 'value' attribute's value
                        var val = node.Attributes["value"].Value;

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            } 

这是XML文档:

<InsurancePolicy xmlns:zzzlocal="com.zzz100.policy.data.local" schemaVersion="2.7" variant="multiterm">
<Identifiers>
<Identifier name="VendorPolicyId" value="AAAA"/>
<Identifier name="CompanyPolicyId" value="BBBB"/>
<Identifier name="QuoteNumber" value="CCCC"/>
<Identifier name="pxServerIndex" value="DDDD"/>
<Identifier name="PolicyID" value="EEEE"/>
</Identifiers>
</InsurancePolicy>

过去6个小时我一直试图解决这个问题。老实说,这很糟糕。

2 个答案:

答案 0 :(得分:1)

尝试使用此

//Identifier[@name='CompanyPolicyId']"

或以下不同的方法

XElement rootElement = XElement.Load(<url here>);
string targetValue =
  (string)rootElement.Elements("Identifier")
  .Single(e => (string)e.Attribute("name") == "CompanyPolicyId")
  .Attribute("value");

这假设您希望能够按名称定位其中一个标识符节点,并且您确定将有一个具有该名称的元素。如果不是这样,那么.Single调用将在未找到该节点的情况下抛出异常。

如果您需要使用凭据并希望使用WebClient,则可以使用以下内容: (注意,我没有进行异常处理,检查流可用性,或以其他方式处理/关闭流,只是一个如何让它“工作”的例子)

string uri = "> url here! <";
System.Net.WebClient wc = new System.Net.WebClient();
StreamReader sr = new StreamReader(wc.OpenRead(uri));
string xml = sr.ReadToEnd();
XElement rootElement = XElement.Parse(xml);
string targetValue =
  (string)rootElement.Elements("Identifier")
  .Single(e => (string)e.Attribute("name") == "CompanyPolicyId")
  .Attribute("value");

答案 1 :(得分:0)

这是更简单的版本

    [Test]
    public void Test()
    {
        XElement root = XElement.Load(@"C:\1.xml");
        XElement identifier = GetIdentifierByName(root, "CompanyPolicyId");
        if (identifier == null)
        {
            return;
        }
        Console.WriteLine(identifier.Attribute("value"));
    }

    private static XElement GetIdentifierByName(XContainer root, string name)
    {
        return root.Descendants()
            .Where(x => x.Name.LocalName == "Identifier")
            .FirstOrDefault(x => x.Attribute("name").Value == name);
    }
}

控制台输出为BBBB