【问题标题】:Is there any possible way to access the xml value using loop?有没有可能使用循环访问 xml 值的方法?
【发布时间】:2012-10-05 07:13:06
【问题描述】:

我已将 xml 结构存储到字符串 abcd 中。

    string abcd="<xmlstruct>
    <test>
        <name>testname</name>
        <address>testaddress</address>
        <subject>testsub<subject>
    </test>

    <test1>
        <name>testname1</name>
        <address>testaddress1</address>
        <subject>testsub<subject>
    </test1>

    <test2>
        <name>testname2</name>
        <address>testaddress2</address>
        <subject>testsub2<subject>
    </test2>

    <test3>
        <name>testname3</name>
        <address>testaddress3</address>
        <subject>testsub3<subject>
    </test3>


    </xmlstruct>";

我从字符串中检索了 xml 值,例如,

var xElem = XElement.Parse(abcd);
string getname =  xElem.Element("test").Element("name").Value;
string getname1 = xElem.Element("test1").Element("name").Value;
string getname2 = xElem.Element("test2").Element("name").Value;
string getname3 = xElem.Element("test3").Element("name").Value;

它工作正常。我的问题是,“有没有可能的方法来制作循环并获取测试、test1、test2、test3 值?”

【问题讨论】:

    标签: c# xml c#-4.0 xml-parsing xml-serialization


    【解决方案1】:

    您对"test0" 的选择有点不规则,但应该这样做:

    for (int i = 0; i < N; i++)
    {
       string suffix = i > 0 ? i.ToString() : "";
       string getname =  xElem.Element("test"+suffix).Element("name").Value;
       ...
    }
    

    但您可能应该研究一种更好的 XML 结构,例如

    <test id="1">
        <name>testname2</name>
        <address>testaddress2</address>
        <subject>testsub2<subject>
    </test>
    

    【讨论】:

    • 你能详细说明一下吗?因为我是处理xml的新手
    • 只有当你指出你需要用它做什么时,我才能详细说明。
    • 可能想要将那些x 更改为i,反之亦然:p
    • @HenkHolterman Holterman 字符串后缀 = x > 0 ? x.ToString() : "";在这个语句中 x 代表什么?
    • 抱歉,应该是i。已编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-21
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多