xml анализ с использованием c# (BsonDocument) - PullRequest
2 голосов
/ 05 марта 2020

Ниже находится мой xml файл, и я хочу проанализировать элемент AttributeSets. хочу сохранить все данные в базе данных mongoDB, используя C#

   <AttributeSets>
     <ns2:ItemAttributes xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd" xml:lang="en-GB">
       <ns2:Brand>Ambi Pur</ns2:Brand>
       <ns2:PackageDimensions>
         <ns2:Height Units="inches">2.5590551155</ns2:Height>
         <ns2:Length Units="inches">6.6929133790</ns2:Length>
         <ns2:Width Units="inches">4.5275590505</ns2:Width>
         <ns2:Weight Units="pounds">0.2645547144</ns2:Weight>
       </ns2:PackageDimensions>
     </ns2:ItemAttributes>
   </AttributeSets>

Вот мой код.

foreach (var attribute in attributeSet.Any)
{
    string xmlFile = ProductsUtil.FormatXml((System.Xml.XmlElement)attribute);
    XElement element = XElement.Parse(xmlFile);
    XNamespace ns2 = "http://mws.amazonservices.com/schema/Products/2011-10-01";
    IEnumerable<object> attribute_Set = element.Descendants()
    foreach(System.Xml.Linq.XElement current in attribute_Set)
    {
        if(current.Name.LocalName == "Brand"){
            Item.BRAND = current.Value;
        }
        else if (current.Name.LocalName == "PackageDimensions"){
            var document = new BsonDocument {
                // have no idea how to handle here
            }
        }
    }
}

Ниже атрибут_Set

       <ns2:Brand>Ambi Pur</ns2:Brand>
       <ns2:PackageDimensions>
         <ns2:Height Units="inches">2.5590551155</ns2:Height>
         <ns2:Length Units="inches">6.6929133790</ns2:Length>
         <ns2:Width Units="inches">4.5275590505</ns2:Width>
         <ns2:Weight Units="pounds">0.2645547144</ns2:Weight>
       </ns2:PackageDimensions>

Ниже приведен вывод моего желания (mongoDB JsonView)

"Brand" : "Ambi Pur"
"PackageDimensions" : {
    "Height" : {
        "Units" : "inches",
        "text" : "2.5590551155"
    }
    "Length" : {
        "Units" : "inches",
        "text" : "6.6929133790"
    }...
}

Любые советы и предложения будут с благодарностью.

1 Ответ

1 голос
/ 05 марта 2020

Я бы начал с создания некоторых классов для десериализации вашего xml в:

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class AttributeSets
{
    [System.Xml.Serialization.XmlElementAttribute(Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd")]
    public ItemAttributes ItemAttributes { get; set; }
}

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd", IsNullable = false)]
public partial class ItemAttributes
{
    public string Brand { get; set; }

    public ItemAttributesPackageDimensions PackageDimensions { get; set; }

    [System.Xml.Serialization.XmlAttributeAttribute(Form = System.Xml.Schema.XmlSchemaForm.Qualified, Namespace = "http://www.w3.org/XML/1998/namespace")]
    public string lang { get; set; }
}

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd")]
public partial class ItemAttributesPackageDimensions
{

    public ItemAttributesPackageDimensionsHeight Height { get; set; }
    public ItemAttributesPackageDimensionsLength Length { get; set; }
    public ItemAttributesPackageDimensionsWidth Width { get; set; }
    public ItemAttributesPackageDimensionsWeight Weight { get; set; }
}

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd")]
public partial class ItemAttributesPackageDimensionsHeight
{
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Units { get; set; }

    [System.Xml.Serialization.XmlTextAttribute()]
    public decimal Value { get; set; }
}

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd")]
public partial class ItemAttributesPackageDimensionsLength
{
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Units { get; set; }

    [System.Xml.Serialization.XmlTextAttribute()]
    public decimal Value { get; set; }
}

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd")]
public partial class ItemAttributesPackageDimensionsWidth
{
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Units { get; set; }
    [System.Xml.Serialization.XmlTextAttribute()]
    public decimal Value { get; set; }
}

[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd")]
public partial class ItemAttributesPackageDimensionsWeight
{
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Units { get; set; }

    [System.Xml.Serialization.XmlTextAttribute()]
    public decimal Value { get; set; }
}

Затем мы можем десериализовать его, используя следующий код:

var xml = @"<AttributeSets>
    <ns2:ItemAttributes xmlns:ns2=""http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd"" xml:lang=""en-GB"">
        <ns2:Brand>Ambi Pur</ns2:Brand>
        <ns2:PackageDimensions>
            <ns2:Height Units=""inches"">2.5590551155</ns2:Height>
            <ns2:Length Units=""inches"">6.6929133790</ns2:Length>
            <ns2:Width Units=""inches"">4.5275590505</ns2:Width>
            <ns2:Weight Units=""pounds"">0.2645547144</ns2:Weight>
        </ns2:PackageDimensions>
    </ns2:ItemAttributes>
</AttributeSets>";
using var sr = new StringReader(xml);
var attributeSet = (AttributeSets)new XmlSerializer(typeof(AttributeSets)).Deserialize(sr);

После что мы можем просто вставить его в базу данных, как любой другой C# объект

var client = new MongoClient();
var database = client.GetDatabase("test");
var collection = database.GetCollection<ItemAttributes>("attributeSets");
await collection.InsertOneAsync(attributeSet.ItemAttributes);

Затем мы сможем увидеть его в оболочке mon go:

> use test
switched to db test
> db.attributeSets.find().pretty()
{
        "_id" : ObjectId("5e60ca560b8dbc44bf1a869f"),
        "Brand" : "Ambi Pur",
        "PackageDimensions" : {
                "Height" : {
                        "Units" : "inches",
                        "Value" : "2.5590551155"
                },
                "Length" : {
                        "Units" : "inches",
                        "Value" : "6.6929133790"
                },
                "Width" : {
                        "Units" : "inches",
                        "Value" : "4.5275590505"
                },
                "Weight" : {
                        "Units" : "pounds",
                        "Value" : "0.2645547144"
                }
        },
        "lang" : "en-GB"
}
>
...