当值为null或空字符串时

发布于 2025-02-06 12:22:26 字数 1347 浏览 1 评论 0原文

我可以找到很多人和示例,询问如何隐藏XML标签,但是当值为null或空字符串时,我找不到的是如何将其写入标签。对我来说,无论我尝试过什么,包括添加XMlelement将其标记为nullable false/true(尝试过),除非具有价值,否则永远不会写下MyProperty的标签。

我已经尝试过

[XmlElement(IsNullable = true)]

[XmlElement(IsNullable = false)]

也不有所作为,

这只是对真实代码的模型。保存是这样完成的,因为它是作为现有Xmldocument的一部分保存的,因此还有其他代码可以加载并找到需要添加它的位置和再次保存整个文档。包括所有代码,然后删除IP将是很多工作和代码页面。

public class MyClass
{
    public string MyProperty { get; set; }
}

var myClass = new MyClass();

var xmlSerializer = new XmlSerializer(MyClass.GetType());
var xmlSerializerNamespaces = new XmlSerializerNamespaces();
xmlSerializerNamespaces.Add("", "");
var xmlWriterSettings = new XmlWriterSettings
{
    Indent = true,
    OmitXmlDeclaration = true,
    Async = true
};

using var stringWriter = new StringWriter();
using (var xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings))
{
    xmlSerializer.Serialize(xmlWriter, myClass, xmlSerializerNamespaces);
    await xmlWriter.FlushAsync();
    xmlWriter.Close();
    xmlWriter.Dispose();
}
await stringWriter.FlushAsync();
stringWriter.Close();
await stringWriter.DisposeAsync();

var xDocument = XDocument.Parse(stringWriter.ToString());
xDocument.Descendants().Where(e => string.IsNullOrEmpty(e.Value)).Remove();
xDocument.Save(myClass);

I can find lots of people and examples that ask how to hide the XML tag but what I don't find is when the value is null or empty string how to get it to write the tag. For me no matter what I've tried including adding that XmlElement that marks it as IsNullable false/true (tried both) the tag for MyProperty is never written unless it has a value.

I've tried

[XmlElement(IsNullable = true)]

and

[XmlElement(IsNullable = false)]

neither makes a difference

This is just a mockup of the real code the save is done this way as it's saving it as part of an existing XmlDocument so there is other code that loads and finds where it needs to add it and saves the entire document again. Including all of the code and then removing IP would be a lot of work and pages of code.

public class MyClass
{
    public string MyProperty { get; set; }
}

var myClass = new MyClass();

var xmlSerializer = new XmlSerializer(MyClass.GetType());
var xmlSerializerNamespaces = new XmlSerializerNamespaces();
xmlSerializerNamespaces.Add("", "");
var xmlWriterSettings = new XmlWriterSettings
{
    Indent = true,
    OmitXmlDeclaration = true,
    Async = true
};

using var stringWriter = new StringWriter();
using (var xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings))
{
    xmlSerializer.Serialize(xmlWriter, myClass, xmlSerializerNamespaces);
    await xmlWriter.FlushAsync();
    xmlWriter.Close();
    xmlWriter.Dispose();
}
await stringWriter.FlushAsync();
stringWriter.Close();
await stringWriter.DisposeAsync();

var xDocument = XDocument.Parse(stringWriter.ToString());
xDocument.Descendants().Where(e => string.IsNullOrEmpty(e.Value)).Remove();
xDocument.Save(myClass);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如果没有你 2025-02-13 12:22:26

尝试以下内容已使用.NET 6:

使用语句

  • 使用System.xml;
  • 使用Sytem.xml.Serialization;

serializetoxmlfile :

private void SerializeToXMLFile(object obj, string xmlFilename)
{
    if (String.IsNullOrEmpty(xmlFilename))
        throw new Exception($"Error: XML filename not specified. (xmlFilename: '{xmlFilename}')");

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.OmitXmlDeclaration = true;

    using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(xmlFilename, settings))
    {
        //specify namespaces
        System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
        ns.Add(string.Empty, "urn:none");

        //create new instance
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());

        //write XML to file
        serializer.Serialize(writer, obj, ns);
    }
}    

选项1:

创建类(name:myClass)

[XmlRoot("myclass")]
public class MyClass
{
    [XmlElement(ElementName = "myproperty")]
    public string? MyProperty { get; set; } = string.Empty;
}

注意:将值设置为string.string.string.empty < /code>,以便在未设置值时将其保存。

结果

”在此处输入图像描述


选项2:

创建类(name:myClass)

[XmlRoot("myclass")]
public class MyClass
{
    [XmlElement(ElementName = "myproperty", IsNullable = true)]
    public string? MyProperty { get; set; }
}

result


用法

MyClass myClass = new MyClass();
SerializeToXMLFile(myClass, @"C:\Temp\Test.xml");

资源

Try the following it's been tested using .NET 6:

using statements:

  • using System.Xml;
  • using System.Xml.Serialization;

SerializeToXMLFile:

private void SerializeToXMLFile(object obj, string xmlFilename)
{
    if (String.IsNullOrEmpty(xmlFilename))
        throw new Exception(
quot;Error: XML filename not specified. (xmlFilename: '{xmlFilename}')");

    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Indent = true;
    settings.OmitXmlDeclaration = true;

    using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(xmlFilename, settings))
    {
        //specify namespaces
        System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces();
        ns.Add(string.Empty, "urn:none");

        //create new instance
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());

        //write XML to file
        serializer.Serialize(writer, obj, ns);
    }
}    

Option 1:

Create class (name: MyClass)

[XmlRoot("myclass")]
public class MyClass
{
    [XmlElement(ElementName = "myproperty")]
    public string? MyProperty { get; set; } = string.Empty;
}

Note: Set the value to string.Empty so that it's saved when the value isn't set.

Result:

enter image description here


Option 2:

Create class (name: MyClass)

[XmlRoot("myclass")]
public class MyClass
{
    [XmlElement(ElementName = "myproperty", IsNullable = true)]
    public string? MyProperty { get; set; }
}

Result:

enter image description here


Usage:

MyClass myClass = new MyClass();
SerializeToXMLFile(myClass, @"C:\Temp\Test.xml");

Resources:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文