【问题标题】:Xmldocument show value as value attribute in xmlXmldocument 将值显示为 xml 中的值属性
【发布时间】:2017-10-06 11:40:40
【问题描述】:

xmldocument 为我生成所有条目,如下所示

<type>document</type>

我希望它像这样生成

<type value = "document"></type>

有没有简单的方法来做到这一点?

只是为了添加更多细节,我有一个 json,我使用 JsonConvert.DeserializeXmlNode 将其转换为 xml。

当我使用这个 api 进行转换时,我会得到这样的价值 -

<type>document</type>

我希望它是-

<type value = "document"></type>

【问题讨论】:

  • 你是如何生成这个的?您是否在 POCO 对象上使用注释(XmlAttribute、XmlElement)?
  • 不,我没有使用注释,它是 POCO 中的一个简单属性,如下所示 - public BundleType Type { get;放; } 其中 Bundletype 值是文档

标签: c# xml xmldocument


【解决方案1】:

这里是生成属性的示例代码。

XmlDocument doc = new XmlDocument();
XmlNode node = doc.CreateNode(XmlNodeType.Element, "type", "");
XmlAttribute attr = doc.CreateAttribute("value");
attr.Value = "Document";
node.Attributes.Append(attr);
doc.AppendChild(node);
var outputString = doc.InnerXml;

【讨论】:

    【解决方案2】:

    我更喜欢用于 XML 创建的 XML Linq 类。书写和阅读要容易得多。 您可以将其与“使用 System.Xml.Linq;”绑定。 现在您可以使用“new XAttribute”在元素中创建一个属性。

    这是一个小例子:

            //build base
            XNamespace myNs = "http://www.w3.org/2001/XMLSchema-instance";
            XDocument myDoc = new XDocument(
                new XDeclaration("1.0", "UTF-8", null),
                new XElement("newDocument",
                    new XAttribute(XNamespace.Xmlns + "xsi", myNs),
                    new XAttribute(myNs + "noNamespaceSchemaLocation", "ArchiveDocument.xsd"),
                    new XElement("document",
                        new XAttribute("instanceDate", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")),
                        new XElement("attribute",
                            new XAttribute("attributeDefinitionId", "Belegart"),
                            new XElement("value", reportType)),
                        new XElement("attribute",
                            new XAttribute("attributeDefinitionId", "Date"),
                            new XElement("value", Date.ToString("yyyyMMdd"))),
                        new XElement("attribute",
                            new XAttribute("attributeDefinitionId", "Kalenderjahr"),
                            new XElement("value", Date.ToString("yyyy"))),
                        new XElement("attribute",
                            new XAttribute("attributeDefinitionId", "Kalendermonat"),
                            new XElement("value", Date.Month.ToString())),
                        new XElement("attribute",
                            new XAttribute("attributeDefinitionId", "Mitglieds_Nummer"),
                            new XElement("value", partnerId.ToString())))));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      相关资源
      最近更新 更多