gpt4 book ai didi

c# - 为什么我使用 LINQ to XML 得到额外的 xmlns =""?

转载 作者:太空宇宙 更新时间:2023-11-03 11:47:58 25 4
gpt4 key购买 nike

我正在使用 LINQ to XML 生成一段 XML。一切都很好,除了我以某种方式抛出一些空的命名空间声明。有没有人知道我做错了什么?这是我的代码

    private string SerializeInventory(IEnumerable<InventoryInformation> inventory)
{
var zones = inventory.Select(c => new {
c.ZoneId
, c.ZoneName
, c.Direction
}).Distinct();

XNamespace ns = "http://www.dummy-tmdd-address";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";

var xml = new XElement(ns + "InventoryList"
, new XAttribute(XNamespace.Xmlns + "xsi", xsi)
, zones.Select(station => new XElement("StationInventory"
, new XElement("station-id", station.ZoneId)
, new XElement("station-name", station.ZoneName)
, new XElement("station-travel-direction", station.Direction)
, new XElement("detector-list"
, inventory.Where(p => p.ZoneId == station.ZoneId).Select(plaza =>
new XElement("detector", new XElement("detector-id", plaza.PlazaId)))))));

xml.Save(@"c:\tmpXml\myXmlDoc.xml");
return xml.ToString();
}

这是生成的 xml。我希望它正确呈现?浏览器可能会隐藏标签。

<InventoryList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.dummy-tmdd-address">
<StationInventory xmlns="">
<station-id>999</station-id>
<station-name>Zone 999-SEB</station-name>
<station-travel-direction>SEB</station-travel-direction>
<detector-list>
<detector>
<detector-id>7503</detector-id>
</detector>
<detector>
<detector-id>2705</detector-id>
</detector>
</detector-list>
</StationInventory>
</InventoryList>

请注意第一个子元素中的空命名空间声明。有什么办法可以解决这个问题吗?任何提示当然值得赞赏。

谢谢大家

最佳答案

由于缺少命名空间:

new XElement("StationInventory"... 

这隐含地指示 StationInvetory 元素的空 namespace “”。你应该这样做:

new XElement(ns + "StationInventory"...

请注意,您必须对您创建的位于 ns 命名空间中的任何元素执行此操作。 XML 序列化程序将确保根据范围使用正确的命名空间前缀来限定元素。

关于c# - 为什么我使用 LINQ to XML 得到额外的 xmlns =""?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2922531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com