2012-03-26 34 views
0

我试图改变情境中的计数属性的属性值,则XML如下设置在XML

<ServiceConfiguration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns:xsd="http://www.w3.org/2001/XMLSchema" serviceName="" osFamily="1" osVersion="*"  
xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration"> 
<Role name="WebRole1"> 
    <ConfigurationSettings> 
     <Setting name="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" /> 
    </ConfigurationSettings> 
    <Instances count="1" /> 
    <Certificates /> 
</Role> 
</ServiceConfiguration> 

我已经试过,我在另一个问题看见下面的,但我得到的错误“对象引用未设置为对象的实例“。

changeConfigXDoc.Root.Element("ServiceConfiguration").Element("Role").Element("Instances").Attribute("count").Value=ChangeInstanceText.Text; 
+2

我想你可以摆脱'.Root.Element( “ServiceConfiguration”)'的,假设你的'changeConfigXDoc'代表上述XML的。或者试试删除'.Root'。 – 2012-03-26 21:15:07

+0

尝试了两种方法,并且我继续得到错误“对象引用未设置为对象的实例”。 – StevenR 2012-03-26 21:57:16

+0

试着将你的Root.Element链分离出来分离变量,以帮助确定Object未设置引用的位置。这可能会帮助您识别错误? – dreza 2012-03-26 22:06:45

回答

1

你应该花命名空间考虑

XNamespace ns = XNamespace.Get("http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration"); 
changeConfigXDoc 
    .Element(ns + "ServiceConfiguration") 
    .Element(ns + "Role") 
    .Element(ns + "Instances") 
    .Attribute("count").Value = ChangeInstanceText.Text; 

或者

XNamespace ns = XNamespace.Get("http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration"); 
changeConfigXDoc 
    .Descendants(ns+"Instances") 
    .First() 
    .Attribute("count").Value = "666"; 
+0

天才!谢谢您的帮助 – StevenR 2012-03-26 22:24:18

1

Root是<ServiceConfiguration />节点,尝试这样做,而不是:

changeConfigXDoc.Root.Element("Role") 
        .Element("Instances") 
        .Attribute("count").Value = ChangeInstanceText.Text; 

添加these extension methods再试试这个,

changeConfigXDoc.Root.Set("Role/Instances/count", ChangeInstanceText.Text, true); 
+0

尝试过这一点,我仍然得到“对象引用未设置为对象的实例。” – StevenR 2012-03-26 21:56:46

+0

尝试我在帖子后添加的 – 2012-03-27 01:03:01