Xpath选择所有属性

时间:2013-11-25 14:55:49

标签: c# xml xpath

我在c#类中有下面的xml。

string xml =@"<?xml version='1.0' encoding='UTF-8'?>
<call method='importCube'>
<credentials login='sampleuser@company.com' password='my_pwd' instanceCode='INSTANCE1'/>
<importDataOptions version='Plan' allowParallel='false' moveBPtr='false'/>

我需要更新节点属性中的XML,即

string xml =@"<?xml version='1.0' encoding='UTF-8'?>
<call method='importCube'>
<credentials login='testuser@test.com' password='userpassword' instanceCode='userinstance'/>
<importDataOptions version='Actual' allowParallel='true' moveBPtr='true'/>

我已经编写了代码来执行此操作:

// instantiate XmlDocument and load XML from string
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

// get a list of nodes
XmlNodeList aNodes = doc.SelectNodes("/call/credentials");


// loop through all nodes
foreach (XmlNode aNode in aNodes)
{
    // grab the attribute
    XmlAttribute idLogin = aNode.Attributes["login"];
    XmlAttribute idPass = aNode.Attributes["password"];
    XmlAttribute idInstance = aNode.Attributes["instanceCode"];

    idLogin.Value = "myemail.com";
    idPass.Value = "passtest";
    idInstance.Value = "TestInstance";



    }

它可以工作,但问题是我必须为每个节点路径重复整个代码块,即

XmlNodeList aNodes = doc.SelectNodes("/call/importDataOptions");
....

必须有更好的方法。我有什么想法可以在1遍传递属性吗?

1 个答案:

答案 0 :(得分:1)

也许只使用强制转换为XmlElement可以帮助您减少代码:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

foreach (XmlElement credential in doc.SelectNodes("/call/credentials"))
{
    credential.SetAttribute("login"       , "myemail.com" );
    credential.SetAttribute("password"    , "passtest"    );
    credential.SetAttribute("instanceCode", "TestInstance");
}

另一种选择是创建一个类似于你的XML词汇表的对象结构,并将你的输入反序列化为那些对象,但它似乎有点过分。

编辑:根据您的评论,您可以选择:

foreach (XmlElement node in doc.SelectNodes("/call/*")) // it's case sensitive
{
    switch(node.Name)
    {
        case "credentials":
            node.SetAttribute("login"       , "myemail.com" );
            node.SetAttribute("password"    , "passtest"    );
            node.SetAttribute("instanceCode", "TestInstance");
            break;
        case "importDataOptions":
            // ...
            break;
        default:
            throw new ArgumentOutOfRangeException("Unexpected node: "+node.Name);
    }
}