Установка значения атрибута в XML - PullRequest
0 голосов
/ 27 марта 2012

я пытаюсь изменить атрибут count в экземплярах, 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 ]

1 голос
/ 27 марта 2012

Вы должны принять во внимание пространство имен

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";
1 голос
/ 27 марта 2012

Root - это узел <ServiceConfiguration />, попробуйте сделать это вместо этого:

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

Добавьте эти методы расширения , а затем попробуйте это,

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