0

私の質問を読んでくれてありがとう。

下が私のxmlファイルのサンプルです。参考にしてください。

以前にいくつかのxmlファイルを作成しましたが、「CMarkXml」によるものです。「IntoElement、OutofElement」は非常に明確です。

しかし、C#...私が失われたとき..

1: タグ名を使用せずに xml ファイルを読み書きする方法。xmlファイルをC#で操作するという記事をいくつか見かけますが、どれもタグ名はわかっていると思います。

2: タグ名がない場合、非常に難しいか、お勧めしません。次に、XmlDocument で xml ファイルを読み書きする方法を教えてください。(申し訳ありませんが、Lingはご遠慮ください。私はそれが非常に苦手です...)。

3: 私の考えでは、xml ファイルの場合、いくつかのセクションを取得します。xmldocument でセクションを解析することはできます。

4:もちろん、xmlファイルの書き込み/変更のために、いくつかのセクションの削除、いくつかの「リーフ」の削除、属性の変更を含める必要があります...

長い質問を読んでいただき、ありがとうございます。良いサンプル コードをお持ちで、ここに貼り付けていただけない場合は、「erlvde@gmail.com」までお送りいただけますでしょうか。

<root>
    <a>i belong to a</a>
    <b>
        <bb>
            <bb>1</bb>
            <bb>2</bb>
            <bb>3</bb>
            <bb>4</bb>
            <bb>5</bb>
        </bb>
        <bb>
            <bb>1</bb>
            <bb>2</bb>
            <bb>3</bb>
            <bb>4</bb>
            <bb>5</bb>
        <bb>
    ....(other <bb>)
    </b>
</root>
4

6 に答える 6

2

xmlを次のように読み込みますXmlDocument

var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("XML HERE");

子ノードへのアクセス:

xmlDocument.ChildNodes[1]

しかし、それは非常にエラーが発生しやすいことも事実です

子ノードがあるかどうかを確認することもできます。

xmlDocument.HasChildNodes

そして、子ノードの数を取得します。

xmlDocument.ChildNodes.Count
于 2012-04-18T11:37:40.623 に答える
1

要素名に識別子が含まれているように見えます。その場合、XML スキーマを制御できる場合は、XML を変更して識別子を示す要素や属性を含め、組み込みのXmlSerializerクラスを使用して XML との間でシリアル化することを強くお勧めします。出力をフォーマットするために、XmlElementXmlAttributeなど、多くの修飾子を使用できます。

これは、開始するためのチュートリアルです。

可能であれば、XML を次のようなものに変更します。これにより、操作がはるかに簡単になります...スキーマを変更する可能性がある場合は、もう一度。

<root>
    <a>i belong to a</a>
    <b>
        <bb id="1">
            <bb>1</bb>
            <bb>2</bb>
            <bb>3</bb>
            <bb>4</bb>
            <bb>5</bb>
        </bb>
        <bb id="2">
            <bb>1</bb>
            <bb>2</bb>
            <bb>3</bb>
            <bb>4</bb>
            <bb>5</bb>
        <bb>
    </b>
</root>

編集 この編集には、XML に加えた変更が反映されます


以下は、オブジェクトを XML ファイルにシリアル化し、再水和する簡単なコンソール アプリケーションです。

期待される XML

<?xml version="1.0" encoding="utf-8"?>
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <a>i belong to a</a>
  <b>
    <bb>
      <bb>1</bb>
      <bb>2</bb>
      <bb>3</bb>
      <bb>4</bb>
      <bb>5</bb>
    </bb>
    <bb>
      <bb>1</bb>
      <bb>2</bb>
      <bb>3</bb>
      <bb>4</bb>
      <bb>5</bb>
    </bb>
  </b>
</root>

簡単なコンソール アプリケーションのデモ

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var items = new root
            {
                a = "i belong to a",
                b = new List<bb>
                {
                    new bb
                    {
                        bbClassProperty = new List<int>
                        {
                            1,
                            2,
                            3,
                            4,
                            5
                        }
                    },
                    new bb
                    {
                        bbClassProperty= new List<int>
                        {
                            1,
                            2,
                            3,
                            4,
                            5
                        }
                    }
                }
            };

            XmlSerializer serializer = new XmlSerializer(typeof(root));

            using (var textWriter = new StreamWriter(@"C:\root.xml"))
            {
                serializer.Serialize(textWriter, items);
                textWriter.Close();
            }

            using (var stream = new StreamReader(@"C:\root.xml"))
            {
                var yourObject = serializer.Deserialize(stream);
            }

            Console.Read();
        }
    }

    #region [Classes]

    public class root
    {
        public string a { get; set; }

        public List<bb> b { get; set; }
    }

    public class bb
    {
        [XmlElement("bb")]
        public List<int> bbClassProperty { get; set; }
    }

    #endregion
}
于 2012-04-18T11:43:24.873 に答える
0

XmlNodeオブジェクトがある場合は、XMLNode.FirstChildを使用して、子がある場合はそれを取得できます。XMLNode.NextSiblingを使用して、同じ親ノードの次のノードを取得することもできます。ノードの名前を使用できないのはなぜですか?これが最も簡単で一般的な方法です。特にXPathなどを使用する場合。

XPathは、2番目の質問に対する答えでもあります。

于 2012-04-18T11:38:12.563 に答える
0

オブジェクトのChildNodes(および同様の) プロパティとメソッドを調べXmlElementます。これらにより、ノードの子を反復処理できるようになり、そのノードにその名前を尋ねることができます。

于 2012-04-18T11:33:25.900 に答える
0

クラス XML リーダーを使用できます。簡単な例をここに示します。

using System;
using System.Xml;

class Program
{
    static void Main()
    {
    // Create an XML reader for this file.
    using (XmlReader reader = XmlReader.Create("perls.xml"))
    {
        while (reader.Read())
        {
        // Only detect start elements.
        if (reader.IsStartElement())
        {
            // Get element name and switch on it.
            switch (reader.Name)
            {
            case "perls":
                // Detect this element.
                Console.WriteLine("Start <perls> element.");
                break;
            case "article":
                // Detect this article element.
                Console.WriteLine("Start <article> element.");
                // Search for the attribute name on this current node.
                string attribute = reader["name"];
                if (attribute != null)
                {
                Console.WriteLine("  Has attribute name: " + attribute);
                }
                // Next read will contain text.
                if (reader.Read())
                {
                Console.WriteLine("  Text node: " + reader.Value.Trim());
                }
                break;
            }
        }
        }
    }
    }
}

入力ファイルのテキストは次のとおりです。

<?xml version="1.0" encoding="utf-8" ?>
<perls>
    <article name="backgroundworker">
    Example text.
    </article>
    <article name="threadpool">
    More text.
    </article>
    <article></article>
    <article>Final text.</article>
</perls>

出力

開始要素。

開始要素。

属性名を持つ: backgroundworker

テキスト ノード: サンプル テキスト。

開始要素。

属性名を持つ: スレッドプール

テキスト ノード: 追加のテキスト。

開始要素。

テキスト ノード:

開始要素。

テキスト ノード: 最終テキスト。enter code here

上記の例で、ファイルにヘッダーが含まれていない場合は、次のコードを使用できます。

XmlReaderSettings settings = new XmlReaderSettings();
                settings.ConformanceLevel = ConformanceLevel.Fragment;
reader = XmlReader.Create(filePath, settings)
于 2012-04-18T11:49:20.060 に答える
0

このようなものは役に立ちますか?

void Iterate(XmlNode parent) {
    //do something with
    //parent.Name
    //parent.Value
    //parent.Attributes

    foreach(XmlNode child in parent.ChildNodes) {
        Iterate(child);
    }
}

XmlDocument document = new XmlDocument();
document.Load(filename);

XmlNode parent = document.DocumentElement;
Iterate(parent);

そのように保存することもできます(構文エラーで申し訳ありませんが、実行しませんでした)

public class Document {
    public Element DocumentElement { set; get; }

    private void Load(string fileName) {
        XmlDocument document = new XmlDocument();
        document.Load(fileName);

        DocumentElement = new Element(this, null);
        DocumentElement.Load(document.DocumentElement);
    }
}

public class Element {
    public string Name { set; get; }
    public string Value { set; get; }
    //other attributes

    private Document document = null;
    private Element parent = null;
    public Element Parent { get { return parent; } }
    public List<Element> Children { set; get; }
    private int order = 0;

    public Element(Document document, Element parent) {
        Name = "";
        Value = "";
        Children = new List<LayoutElement>();

        this.document = document;
        this.parent = parent;
        order = parent != null ? parent.Children.Count + 1 : 1;
    }

    private Element GetSibling(bool left) {
        if(parent == null) return null;
        int add = left ? -1 : +1;
        Element sibling = parent.Children.Find(child => child.order == order + add);
        return sibling;
    }

    public Element GetLeftSibling() {
        return GetSibling(true);
    }

    public Element GetRightSibling() {
        return GetSibling(false);
    }

    public void Load(XmlNode node) {
        Name = node.Name;
        Value = node.Value;
        //other attributes

        foreach(XmlNode nodeChild in node.Children) {
            Element child = new Element(document, this);
            child.Load(nodeChild);
            Children.Add(child);
        }
    }
}

Document document = new Document();
document.Load(fileName);

今すぐ変更/削除するには、ツリーを反復して名前で要素を見つけることができますが、名前は一意ではないため、一度に多くの要素に影響を与えることになります。次のようなすべてのタグに一意のIDを追加できます

<bb id="bb1"/>

次に、次のような Load 関数で読み取ります

id = ((XmlElement)node).GetAttribute("id");

この ID を使用してツリーを反復処理します。申し訳ありませんが、今は詳細を提供する時間がありません。

于 2012-04-18T13:17:58.460 に答える