第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

使用 C# 為 XmlSerializer 初始化 XML 成員

使用 C# 為 XmlSerializer 初始化 XML 成員

C#
慕尼黑的夜晚無繁華 2022-01-09 15:05:58
我有以下 XML,需要反序列化以獲取“ThreadGroup.num_threads”、“ThreadGroup.ramp_time”、“HTTPSampler.path”和“HTTPSampler.domain”的值。    <TestPlan>        <hashTree>            <hashTree>                <ThreadGroup>                    <stringProp name="ThreadGroup.on_sample_error">continue</stringProp>                    <stringProp name="ThreadGroup.num_threads">10</stringProp>                    <stringProp name="ThreadGroup.ramp_time">1</stringProp>                    <longProp name="ThreadGroup.start_time">1517853259000</longProp>                    <longProp name="ThreadGroup.end_time">1517853259000</longProp>                    <boolProp name="ThreadGroup.scheduler">false</boolProp>                    <stringProp name="ThreadGroup.duration"></stringProp>                    <stringProp name="ThreadGroup.delay"></stringProp>                </ThreadGroup>                <hashTree>                    <hashTree>                        <HTTPSamplerProxy>                        </HTTPSamplerProxy>                    </hashTree>                </hashTree>            </hashTree>        </hashTree>    </TestPlan>上面的代碼給出了具有許多附加屬性值的所需值,并且代碼似乎也很長。但是,我需要這 4 個(gè)值。請(qǐng)?zhí)岢鋈魏胃玫慕鉀Q方案。
查看完整描述

3 回答

?
Helenr

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個(gè)贊

我已經(jīng)更新了它以使其易于使用。


我開始之前,我決定,你可能想的可能性longProps在HTTPSamplerProxy部分。它還使編碼(很多)更容易和更清潔。我已經(jīng)在沒有任何 longProps 的情況下對(duì)其進(jìn)行了測試,只是為了確保它以您期望的方式與現(xiàn)有 XML 一起工作。


原流程

對(duì)原始描述的更新以斜體顯示


我所做的是使用標(biāo)準(zhǔn)的 XSD.exe 工具獲取您的源 XML 文件(在 HTTPSamplerProxy 部分中有一個(gè)額外的 longProp)并創(chuàng)建一個(gè) XSD。然后我再次使用 XSD.exe 創(chuàng)建了一個(gè)(非常丑陋的)C# 文件。那時(shí),整個(gè)混亂的根源是 TestPlan 類。這是 XSD.exe 生成的內(nèi)容(更新 - 對(duì)新發(fā)出的 XSD.exe 代碼的唯一更改是頂部的命名空間聲明):


/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]

[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]

public partial class hashTree {


    private hashTreeHTTPSamplerProxy[] hTTPSamplerProxyField;


    private hashTree[] hashTree1Field;


    private hashTreeThreadGroup[] threadGroupField;


    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("HTTPSamplerProxy", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]

    public hashTreeHTTPSamplerProxy[] HTTPSamplerProxy {

        get {

            return this.hTTPSamplerProxyField;

        }

        set {

            this.hTTPSamplerProxyField = value;

        }

    }


    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("hashTree")]

    public hashTree[] hashTree1 {

        get {

            return this.hashTree1Field;

        }

        set {

            this.hashTree1Field = value;

        }

    }


    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("ThreadGroup", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]

    public hashTreeThreadGroup[] ThreadGroup {

        get {

            return this.threadGroupField;

        }

        set {

            this.threadGroupField = value;

        }

    }

}


/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]

public partial class hashTreeHTTPSamplerProxy {


    private longProp[] longPropField;


    private stringProp[] stringPropField;


    private boolProp[] boolPropField;


    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("longProp", IsNullable = true)]

    public longProp[] longProp {

        get {

            return this.longPropField;

        }

        set {

            this.longPropField = value;

        }

    }


    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("stringProp", IsNullable = true)]

    public stringProp[] stringProp {

        get {

            return this.stringPropField;

        }

        set {

            this.stringPropField = value;

        }

    }


    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("boolProp", IsNullable = true)]

    public boolProp[] boolProp {

        get {

            return this.boolPropField;

        }

        set {

            this.boolPropField = value;

        }

    }

}


/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]

[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]

public partial class longProp {


    private string nameField;


    private string valueField;


    /// <remarks/>

    [System.Xml.Serialization.XmlAttributeAttribute()]

    public string name {

        get {

            return this.nameField;

        }

        set {

            this.nameField = value;

        }

    }


    /// <remarks/>

    [System.Xml.Serialization.XmlTextAttribute()]

    public string Value {

        get {

            return this.valueField;

        }

        set {

            this.valueField = value;

        }

    }

}


/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]

[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]

public partial class stringProp {


    private string nameField;


    private string valueField;


    /// <remarks/>

    [System.Xml.Serialization.XmlAttributeAttribute()]

    public string name {

        get {

            return this.nameField;

        }

        set {

            this.nameField = value;

        }

    }


    /// <remarks/>

    [System.Xml.Serialization.XmlTextAttribute()]

    public string Value {

        get {

            return this.valueField;

        }

        set {

            this.valueField = value;

        }

    }

}


/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]

[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]

public partial class boolProp {


    private string nameField;


    private string valueField;


    /// <remarks/>

    [System.Xml.Serialization.XmlAttributeAttribute()]

    public string name {

        get {

            return this.nameField;

        }

        set {

            this.nameField = value;

        }

    }


    /// <remarks/>

    [System.Xml.Serialization.XmlTextAttribute()]

    public string Value {

        get {

            return this.valueField;

        }

        set {

            this.valueField = value;

        }

    }

}


/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]

public partial class hashTreeThreadGroup {


    private stringProp[] stringPropField;


    private longProp[] longPropField;


    private boolProp[] boolPropField;


    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("stringProp", IsNullable = true)]

    public stringProp[] stringProp {

        get {

            return this.stringPropField;

        }

        set {

            this.stringPropField = value;

        }

    }


    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("longProp", IsNullable = true)]

    public longProp[] longProp {

        get {

            return this.longPropField;

        }

        set {

            this.longPropField = value;

        }

    }


    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("boolProp", IsNullable = true)]

    public boolProp[] boolProp {

        get {

            return this.boolPropField;

        }

        set {

            this.boolPropField = value;

        }

    }

}


/// <remarks/>

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]

[System.SerializableAttribute()]

[System.Diagnostics.DebuggerStepThroughAttribute()]

[System.ComponentModel.DesignerCategoryAttribute("code")]

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]

[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]

public partial class TestPlan {


    private object[] itemsField;


    /// <remarks/>

    [System.Xml.Serialization.XmlElementAttribute("boolProp", typeof(boolProp), IsNullable = true)]

    [System.Xml.Serialization.XmlElementAttribute("hashTree", typeof(hashTree))]

    [System.Xml.Serialization.XmlElementAttribute("longProp", typeof(longProp), IsNullable = true)]

    [System.Xml.Serialization.XmlElementAttribute("stringProp", typeof(stringProp), IsNullable = true)]

    public object[] Items {

        get {

            return this.itemsField;

        }

        set {

            this.itemsField = value;

        }

    }

}

其余的大部分是新的

XSD.exe 發(fā)出的代碼創(chuàng)建了一組部分類。我在一個(gè)單獨(dú)的源文件中以幾種方式擴(kuò)展了部分類。但是,在開始之前,我聲明了一個(gè)接口和一個(gè)靜態(tài)工作類。


public interface IGrouping {

    boolProp[] boolProp { get; }

    stringProp[] stringProp { get; }

    longProp[] longProp { get; }


    Dictionary<string, bool?> BoolProperties { get; }

    Dictionary<string, long?> LongProperties { get; }

    Dictionary<string, string> StringProperties { get; }

}


public static class PropertyGrouper  {

    public static void GroupProperties(IGrouping itemToGroup) {

        //has this been done before, if yes, return

        if (itemToGroup.StringProperties.Count > 0 || itemToGroup.BoolProperties.Count > 0 || itemToGroup.LongProperties.Count > 0 ) {

            return;

        }

        //otherwise

        if (itemToGroup.boolProp != null) {

            foreach (var bProp in itemToGroup.boolProp) {

                var succeeded = bool.TryParse(bProp.Value, out var bValue);

                itemToGroup.BoolProperties.Add(bProp.name, succeeded ? bValue : (bool?)null);

            }

        }

        if (itemToGroup.longProp != null) {

            foreach (var lProp in itemToGroup.longProp) {

                var succeeded = long.TryParse(lProp.Value, out var lValue);

                itemToGroup.LongProperties.Add(lProp.name, succeeded ? lValue : (long?)null);

            }

        }

        if (itemToGroup.stringProp != null) {

            foreach (var sProp in itemToGroup.stringProp) {

                itemToGroup.StringProperties.Add(sProp.name, sProp.Value);

            }

        }

    }

}

有了這些,我擴(kuò)展了每個(gè) XSD.exe 發(fā)出的類。這TestPlan門課很簡單——我只是添加了一個(gè)類型化的屬性:


public partial class TestPlan {

    [XmlIgnore]

    public hashTree HashTree => Items[0] as hashTree;

}

在hashTreeThreadGroup與hashTreeHTTPSamplerProxy類相同的方式(請(qǐng)記住,我沒有點(diǎn)名任何這些類的,XSD.EXE從XML命名他們)進(jìn)行了擴(kuò)展。每個(gè)都被聲明為實(shí)現(xiàn)IGrouping接口,并且每個(gè)都有 3 個(gè)屬性字典(根據(jù) 的要求IGrouping)。IGrouping接口中的三個(gè)數(shù)組位于XSD 發(fā)出的代碼中:


public partial class hashTreeThreadGroup : IGrouping {

    [XmlIgnore]

    public Dictionary<string, bool?> BoolProperties { get; } = new Dictionary<string, bool?>();

    [XmlIgnore]

    public Dictionary<string, long?> LongProperties { get; } = new Dictionary<string, long?>();

    [XmlIgnore]

    public Dictionary<string, string> StringProperties { get; } = new Dictionary<string, string>();

}


public partial class hashTreeHTTPSamplerProxy : IGrouping {

    [XmlIgnore]

    public Dictionary<string, bool?> BoolProperties { get; } = new Dictionary<string, bool?>();

    [XmlIgnore]

    public Dictionary<string, long?> LongProperties { get; } = new Dictionary<string, long?>();

    [XmlIgnore]

    public Dictionary<string, string> StringProperties { get; } = new Dictionary<string, string>();

}

最后,我延長了hashTree課程。我添加了三個(gè)類型化的屬性,每個(gè)都有一個(gè)空檢查以使事情變得干凈。ThreadGroupItem 和 HttpSamplerProxyItem 屬性分別調(diào)用PropertyGrouper.GroupProperties. 第一次調(diào)用時(shí),XmlSerializer 創(chuàng)建的屬性數(shù)組中的屬性被復(fù)制到字典中。


public partial class hashTree {

    [XmlIgnore]

    public hashTree HashTree {

        get {

            if (hashTree1 != null) {

                return hashTree1[0] as hashTree;

            } else {

                return null;

            }

        }

    }



    [XmlIgnore]

    public hashTreeThreadGroup ThreadGroupItem {

        get {

            if (ThreadGroup != null) {

                var threadGroup = ThreadGroup[0]; // as hashTreeThreadGroup;

                PropertyGrouper.GroupProperties(threadGroup);

                return threadGroup;

            } else {

                return null;

            }

        }

    }


    [XmlIgnore]

    public hashTreeHTTPSamplerProxy HttpSamplerProxyItem {

        get {

            if (HTTPSamplerProxy != null) {

                var httpSamplerProxy = HTTPSamplerProxy[0];

                PropertyGrouper.GroupProperties(httpSamplerProxy);

                return httpSamplerProxy;

            } else {

                return null;

            }

        }

    }

}

一切就緒后,我運(yùn)行了相同的代碼。


   TestPlan result;

   using (var stream = new FileStream("source.xml", FileMode.Open, FileAccess.Read)) {

       var serializer = new XmlSerializer(typeof(TestPlan));

       result = (TestPlan)serializer.Deserialize(stream);

   }

此代碼是我使用第一個(gè)示例訪問您的數(shù)據(jù)的方式。


 var numThreadsParsed = long.TryParse((((XmlSerializeForm.hashTree)result.Items[0]).hashTree1[0].ThreadGroup[0].stringProp[1].Value), out var numThreads);

 var httpSamplerPath = ((XmlSerializeForm.hashTree)result.Items[0]).hashTree1[0].hashTree1[0].hashTree1[0].HTTPSamplerProxy[0].stringProp[4].Value;

但是,通過我做了一些簡單的添加(好吧,代碼并沒有那么復(fù)雜,但是做對(duì)了),訪問屬性就更簡潔了:


 string numThreadsParsed = result.HashTree.HashTree.ThreadGroupItem.StringProperties["ThreadGroup.num_threads"];

 long? startTime = result.HashTree.HashTree.ThreadGroupItem.LongProperties["ThreadGroup.start_time"];

 string httpSamplerPath = result.HashTree.HashTree.HashTree.HashTree.HttpSamplerProxyItem.StringProperties["HTTPSampler.path"];

 bool? useKeepAlive = result.HashTree.HashTree.HashTree.HashTree.HttpSamplerProxyItem.BoolProperties["HTTPSampler.use_keepalive"];

給你!


查看完整回答
反對(duì) 回復(fù) 2022-01-09
?
蕪湖不蕪

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超7個(gè)贊

使用外部 lib Cinchoo ETL - 一個(gè)開源庫,您可以輕松獲取所選節(jié)點(diǎn)值,如下所示


定義 .NET 類型


public class TestPlan

{

    [ChoXmlNodeRecordField(XPath = @"/ThreadGroup/stringProp[@name=""ThreadGroup.on_sample_error""]")]

    public string NumThreads { get; set; }

    [ChoXmlNodeRecordField(XPath = @"/ThreadGroup/stringProp[@name=""ThreadGroup.ramp_time""]")]

    public int RampTime { get; set; }


    [ChoXmlNodeRecordField(XPath = @"/hashTree/hashTree/HTTPSamplerProxy/stringProp[@name=""HTTPSampler.path""]")]

    public string Path { get; set; }

    [ChoXmlNodeRecordField(XPath = @"/hashTree/hashTree/HTTPSamplerProxy/stringProp[@name=""HTTPSampler.domain""]")]

    public string Domain { get; set; }

}

然后使用 Cinchoo ETL 反序列化輸入 xml,如下所示


static void Main()

{

    using (var p = new ChoXmlReader<TestPlan>("*** XML file path ***")

        .WithXPath("/TestPlan/hashTree/hashTree")

        )

    {

        foreach (var rec in p)

            Console.WriteLine(rec.Dump());

    }

}

輸出:


-- ChoXmlReaderTest.Program+TestPlan State --

        NumThreads: continue

        RampTime: 1

        Path: /v1/test/test?debug=false

        Domain: www.abc.com/abc-service-api

希望能幫助到你。


免責(zé)聲明:我是這個(gè)庫的作者。


查看完整回答
反對(duì) 回復(fù) 2022-01-09
?
天涯盡頭無女友

TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超9個(gè)贊

使用 xml linq :


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Xml;

using System.Xml.Linq;


namespace ConsoleApplication1

{

    class Program

    {

        const string FILENAME = @"c:\temp\test.xml";

        static void Main(string[] args)

        {

            XmlData data = new XmlData(FILENAME);

        }

    }

    public class XmlData

    {

        public int? num_threads { get; set;}

        public int? ramp_time { get;set;}

        List<SamplerProxy> HTTPSamplerProxies { get;set;}


        public XmlData(string filename)

        {

            XDocument doc = XDocument.Load(filename);


            XElement threadGroup = doc.Descendants("ThreadGroup").FirstOrDefault();

            num_threads = (int?)threadGroup.Elements("stringProp").Where(x => (string)x.Attribute("name") == "ThreadGroup.num_threads").FirstOrDefault();

            ramp_time = (int?)threadGroup.Elements("stringProp").Where(x => (string)x.Attribute("name") == "ThreadGroup.ramp_time").FirstOrDefault();


            HTTPSamplerProxies = doc.Descendants("HTTPSamplerProxy").Select(x => new SamplerProxy() {

                path = (string)x.Elements("stringProp").Where(y => (string)y.Attribute("name") == "HTTPSampler.path").FirstOrDefault(),

                domain = (string)x.Elements("stringProp").Where(y => (string)y.Attribute("name") == "HTTPSampler.domain").FirstOrDefault()

            }).ToList();


        }

    }

    public class SamplerProxy

    {

        public string path { get; set; }

        public string domain { get; set; }

    }

}


查看完整回答
反對(duì) 回復(fù) 2022-01-09
  • 3 回答
  • 0 關(guān)注
  • 240 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)