0

abcd変数のようなxml文字列にxml構造を保存しました.test1、test2、test3はxml構造の一部です

  string abcd="<xmlstruct>
    <test1>
        <name>testname1</name>
        <address>testaddress1</address>
        <subject>testsub1<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>";
4

4 に答える 4

2

理想的には、最初から XML をそのように構成しないでください。要素名の使用は適切ではありません。使用する方が良いでしょう:

<test id="1">
    ...
</test>

<test id="2">
   ...
</test>

これらが元のクラスに個別の変数を使用した結果である場合、変数はおそらく単一のコレクションである必要があることを示唆しています。

ただし、本当にそれらを見つけたい場合は、次のようなものを使用できます。

IEnumerable<string> ListSuffixes(XElement container, XName prefix)
{
    string localPrefix = prefix.Name.LocalName;
    var elements = container.Elements()
                            .Where(x => x.Name.Namespace == prefix.Name.Namespace
                                        && x.Name.LocalName
                                                 .StartsWith(localPrefix));
    foreach (var element in elements)
    {
        yield return element.Name.LocalName.Substring(localPrefix.Length);
    }
}
于 2012-10-15T10:40:22.940 に答える
1

あなたが達成しようとしていることは完全にはわかりませんが、これは XML が通常どのように使用されるかではありません。

上記のような XML からサフィックス (1、2、3) を取得するには、XML を解析し、xmlstruct要素のすべての子を選択してから、文字列操作を使用します。

ただし、サフィックスを属性として個別に保存するなど、代替スキーマの方がおそらく良い考えです

<xmlstruct>
    <test Suffix="1">
        <name>testname1</name>
        <address>testaddress1</address>
        <subject>testsub1<subject>
    </test>
    <test Suffix="2">
        <name>testname2</name>
        <address>testaddress2</address>
        <subject>testsub2<subject>
    </test>
    <test Suffix="3">
        <name>testname3</name>
        <address>testaddress3</address>
        <subject>testsub3<subject>
    </test>
</xmlstruct>

要素名は実際には動的であってはなりません。特定の要素に許可される要素名のリストは、通常、固定 (有限) リストに属している必要があります。

于 2012-10-15T10:39:42.503 に答える
0

これを試すことができます:

Integer.parseInt(s.replaceAll("[\\D]", ""))

これにより、数字の間の非数字も削除されるため、「test1test1x」は 11 になります。

于 2012-10-15T10:39:04.243 に答える
0

これは機能します:

var suffices =
    XDocument
        .Parse(abcd)
        .Element("xmlstruct")
        .Elements()
        .Where(xe => xe.Name.ToString().StartsWith("test"))
        .Select(xe => int.Parse(xe.Name.ToString().Substring(4)));

戻り値:

結果

于 2012-10-15T10:40:48.120 に答える