C# 返回第一个XPath结果的可读方法

C# 返回第一个XPath结果的可读方法,c#,xml,C#,Xml,我的XML结构如下所示: <Root> <Base> <Greeting>Base Hello!</Greeting> <SpecialMessage>Base Special Message</SpecialMessage> <Products> <Product id="001"> &

我的XML结构如下所示:

<Root>
    <Base>
        <Greeting>Base Hello!</Greeting>
        <SpecialMessage>Base Special Message</SpecialMessage>

        <Products>
            <Product id="001">
                <Greeting>Base 001 Hello!</Greeting>
            </Product>
        </Products>
    </Base>

    <Buy>
        <Greeting>Buy Hello!</Greeting>
        <SpecialMessage>Buy Special Message</SpecialMessage>
        <Products>
            <Product id="001">
                <Greeting>Buy 001 Hello!</Greeting>
            </Product>
        </Products>
    </Buy>

    <Rent>
        <Greeting>Rent Hello</Greeting>
    </Rent>
</Root>

虽然它有效,但它看起来很笨拙,读起来有点粗糙。就可读性而言,有更好的方法吗?

一个选项是创建路径集合,并在其上迭代:

string[] paths = {"Level1", "Level2", "Level3", "Level4"};
foreach(string path in paths)
{
    result = RunXPath(xpaths[path], document);
    if (!String.IsNullOrEmpty(result))
        return result;
}
return "";
一般来说,如果你发现自己编写重复的代码,你应该考虑使用循环或方法(或者两者都)。 另外,尽量不要对不同的事情使用相同的变量。选择有意义的名称-这将有助于可读性,并有助于检测错误。这对你的参议员来说不那么冒犯,但足够重要。考虑:

result = RunXPath(xpaths["/document/my:things/rooms[0]/floor"], document);
Print(result);
result = RunXPath(xpaths["/document/my:things/roomate/phone/mobile"], document);
Print(result);
我最近不得不像那样调试代码,并将其重构为:

string floor = RunXPath(xpaths["/document/my:things/rooms[0]/floor"], document);
Print(floor);
string friendMobilePhone = RunXPath(xpaths["/document/my:things/roomate/phone/mobile"], document);
Print(friendMobilePhone);

你为什么不做一个循环呢?RunXPath(xpaths[“Level”+i.ToString()],文档);
string floor = RunXPath(xpaths["/document/my:things/rooms[0]/floor"], document);
Print(floor);
string friendMobilePhone = RunXPath(xpaths["/document/my:things/roomate/phone/mobile"], document);
Print(friendMobilePhone);