C# 使用foreach循环添加xml innertext
我正在尝试向此xml文档的saml:AttributeValue元素添加值:C# 使用foreach循环添加xml innertext,c#,asp.net,xml,saml,C#,Asp.net,Xml,Saml,我正在尝试向此xml文档的saml:AttributeValue元素添加值: <saml:AttributeStatement xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"> <saml:Attribute Name="FNAME"> <saml:AttributeValue></saml:AttributeValue> </saml:Attribute> <saml:
<saml:AttributeStatement xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<saml:Attribute Name="FNAME">
<saml:AttributeValue></saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="LNAME">
<saml:AttributeValue></saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="Gender">
<saml:AttributeValue></saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="UniqueID">
<saml:AttributeValue></saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="DateOfBirth">
<saml:AttributeValue></saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="ClientID">
<saml:AttributeValue></saml:AttributeValue>
</saml:Attribute>
lblTest显示的是我期望的结果——所有6个元素的值都正确,但文档根本没有显示任何值。这是循环并将这些值添加到节点的正确方法吗?在某种程度上,您做的事情是正确的:问题是,您只是在更新XML文档的内存副本
有关如何使用XmlDocument.Save将内存中的更改保存到XML文件的说明,请参阅。如果XML位于文件中,则需要调用assertion.Savefilename。如果它是一个字符串xml,那么您需要创建一个writer并对其进行写入。
//get the AttributeStatement node
XmlNode attrs = assertion.SelectSingleNode("//saml:AttributeStatement", ns1);
//get the Attribute nodes within the AttributeStatement node
XmlNodeList attr = attrs.SelectNodes("//saml:Attribute", ns1);
//foreach node in the Attribute node list get the AttributeValue node and add an innerText value
foreach (XmlNode xn in attr)
{
XmlNode attrValue = xn.SelectSingleNode("//saml:AttributeValue", ns1);
switch (xn.Attributes["Name"].Value)
{
case "FNAME":
attrValue.InnerText = UserInfo.FirstName;
break;
case "LNAME":
attrValue.InnerText = UserInfo.LastName;
break;
case "Gender":
attrValue.InnerText = UserInfo.Email;
break;
case "UniqueID":
attrValue.InnerText = UserInfo.UserID.ToString();
break;
case "DateOfBirth":
attrValue.InnerText = UserInfo.UserID.ToString();
break;
case "ClientID":
attrValue.InnerText = UserInfo.UserID.ToString();
break;
default:
attrValue.InnerText = "No attribute listed";
break;
}
//output each AttributeValue innerText.
lblTest.Text += attrValue.InnerText + " ";
}