I'm building an xml file using XDocument
XDocument single = new XDocument(
new XDeclaration("1.0", "UTF-8", "true"),
new XElement(_namespace + "vcards",
XElement.Parse(BuildCardEntry(contact))));
Inside BuildCardEntry(contact) I'm adding the namespace to every XElement too.
But my code pruduces this
<vcards xmlns="urn:ietf:params:xml:ns:vcard-3.0">
<vcard xmlns="urn:ietf:params:xml:ns:vcard-3.0">
insted of this
<vcards xmlns="urn:ietf:params:xml:ns:vcard-3.0">
<vcard>
Does somebody know, how to solve this?
Use SaveOptions.OmitDuplicateNamespaces parameter when saving xml.
single.Save(..., SaveOptions.OmitDuplicateNamespaces);
Related
I generate a sitemap.xml
XDocument xDoc = new XDocument(
new XDeclaration("1.0", "UTF-8", ""),
new XElement("urlset",
new XAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9"),
new Element (....and so on...)
I get an error
The prefix '' cannot be redefined from '' to 'http://www.sitemaps.org/schemas/sitemap/0.9' within the same start element tag.
Google requires xmlns attribute without any prefix.
Seems that adding default namespace in XDocument is a bit tricky, related question : How to set the default XML namespace for an XDocument
You can try to declare default namespace prefix and use that prefix for all elements within <urlset> like so :
XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
XDocument xDoc = new XDocument(
new XDeclaration("1.0", "UTF-8", ""),
new XElement(ns+"urlset",
new XElement(ns+"otherElement"),
new XElement (....and so on...)
You can solve this problem by using blank namespace like the following:
XNamespace blank = XNamespace.Get(#"http://www.sitemaps.org/schemas/sitemap/0.9");
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement(blank + "urlset",
new XAttribute("xmlns", blank.NamespaceName),
new XElement(blank + "loc", "http://www.abc.eba/"),
new Element (....and so on...)
));
i have been searching around but I cannot seem to find any information on this issue.
if you go to https://support.google.com/webmasters/answer/34648
it says one must add the mobile tag to your xml for it to be crawled properly.
My problem lies in that I have no idea on how to actually make this tag when using XDocument.
Does anyone know how to acutally write this tag
<mobile:mobile/>
using the XElement tag?
I have the following code that generates a document
XNamespace sitemap = XNamespace.Get("http://www.sitemaps.org/schemas/sitemap/0.9");
XNamespace mobile = XNamespace.Get("http://www.google.com/schemas/sitemap-mobile/1.0");
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement(sitemap + "urlset",
new XAttribute(XNamespace.Xmlns + "mobile", mobile))
);
and the following code that builds an element
private XElement BuildSitemapItem(XNamespace ns)
{
XElement urlNode = new XElement(ns + "url",
new XElement(ns +"loc"),
new XElement(ns + "lastmod")
);
return urlNode;
}
I have been stuck on this issue for a while so any help would be appreciated.
You just need to specify the right namespace on your XElement (in this case mobile)
XNamespace mobileNs = "http://www.google.com/schemas/sitemap-mobile/1.0";
new XElement(mobileNs + "mobile")
That will output <mobile:mobile/>
I want to make xml element like this:
<ElementName Type="FirstAttribute" Name="SecondAttribute">Value</Atrybut>
Now I'm doing this in this way:
XmlNode xmlAtrybutNode = xmlDoc.CreateElement("ElementName ");
_xmlAttr = xmlDoc.CreateAttribute("Type");
_xmlAttr.Value = "FirstAttribute";
xmlAtrybutNode.Attributes.Append(_xmlAttr);
_xmlAttr = xmlDoc.CreateAttribute("Name");
_xmlAttr.Value = "SecondAttribute";
xmlAtrybutNode.Attributes.Append(_xmlAttr);
xmlAtrybutNode.InnerText = !string.IsNullOrEmpty(Value)
? SetTextLength(Name, ValueLength)
: string.Empty;
Value is input variable in method.
Is there possibility to make this in another way?
More efficiently?
Can I use xmlWriter? Now i'm using xmlDocument.
You can use Linq to XML.
Basically
XDocument doc = new XDocument();
doc.Add(
new XElement("ElementName", "Value",
new XAttribute("Type", "FirstAttribute"),
new XAttribute("Name", "SecondAttribute")));
will give this xml document
<ElementName Type="FirstAttribute" Name="SecondAttribute">Value</ElementName>
How about tweaking your existing code:
XmlElement el = xmlDoc.CreateElement("ElementName");
el.SetAttribute("Type", "FirstAttribute");
el.SetAttribute("Name", "SecondAttribute");
el.InnerText = ...;
Additional thoughts:
XElement
XmlSerializer (from a class instance)
If you’re on .NET 3.5 (or later), you could use LINQ to XML. Make sure that the System.Xml.Linq assembly is referenced, and that you have a using directive for its eponymous namespace.
XDocument document = new XDocument(
new XElement("ElementName",
new XAttribute("Type", "FirstAttribute"),
new XAttribute("Name", "SecondAttribute"),
value));
If you subsequently want to write the XDocument to a target, you can use its Save method. For debugging, it’s useful to call its ToString method, which returns its XML representation as a string.
Edit: Replying to comment:
If you need to convert the XDocument created above into an XmlDocument instance, you may use code similar to the following:
XmlDocument xmlDocument = new XmlDocument();
using (XmlReader xmlReader = document.CreateReader())
xmlDocument.Load(xmlReader);
What about using LINQ to XML as in this article. That can be very elegant - it can all be done on one line.
XDocument doc = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("element",
new XAttribute("attribute1", "val1"),
new XAttribute("attribute2", "val2"),
)
);
I am creating XML using Linq to XML and C#. It all works great except when I need to manually add in a row in the XML. This row is only added if I have a value to pass through to it, otherwise I just ignore the entire tag.
I use XElement.Load to load in the string of text that I store in a string but when I attach it to the XML it always puts in xmlns="" at the end of my tag.
Is there a way I can tell XElement.Load to use the existing namespace or to ignore it when putting in the string to the XML?
Ideally I just want my string to be included to the XML being created without extra tags being added.
Below is a sample of what I currently do:
string XMLDetails = null;
if (ValuePassedThrough != null)
XMLDetails = "<MyNewTag Code=\"14\" Value=\"" + ValuePassedThrough +"\"></MyNewTag>";
When I build up the XML I load the above string into my XML. It is here where xmlns="" is being added to the XMLDetails value but ideally I want this ignored as it is causing issues with the recipient when they try to read this tag.
XNamespace ns = "http://namespace-address";
XNamespace xsi = "http://XMLSchema-instance-address";
XDocument RequestDoc = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement(ns + "HeaderTag",
new XAttribute("xmlns", ns),
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XAttribute(xsi + "schemaLocation", "http://www.addressofschema.xsd"),
new XAttribute("Version", "1"),
new XElement(ns + "OpeningTAG",
...My XML Code ...
XElement.Load(new StringReader(XMLDetails))
...End of XML Code ...
As mentioned above. My code works, it successfully outputs XML for me. Its just the MyNewTag tag I load in using XElement.Load gets xmlns="" added to the end of it which is causing me an issue.
Any ideas how I can work around this? Thanks for your help.
Regards,
Rich
How about:
XElement withoutNamespace = XElement.Load(new StringReader(XMLDetails));
XElement withNamespace = new XElement(ns + withoutNamespace.Name.LocalName,
withoutNamespace.Nodes());
As a better alternative - why don't you either include the namespace when you're building up the XML, or even better, create an XElement instead of manually generating an XML string which you then read. Manually creating XML is very rarely a good idea. Aside from anything else, you're assuming that ValuePassedThrough has already been escaped, or doesn't need escaping etc. That may be valid - but it's at least a cause for concern.
Like this
XElement XMLDetails = new XElement(ns + "OpeningTAG", new XElement(ns + "MyNewTag", new XAttribute("Code", 14), new XAttribute("Value", 123)));
XDocument RequestDoc = new XDocument(
new XDeclaration("1.0", "utf-8", null),
new XElement(ns + "HeaderTag",
new XAttribute("xmlns", ns),
new XAttribute(XNamespace.Xmlns + "xsi", xsi),
new XAttribute(xsi + "schemaLocation", "http://www.addressofschema.xsd"),
new XAttribute("Version", "1"),
XMLDetails));
I have an existing XDocument object that I would like to add an XML doctype to. For example:
XDocument doc = XDocument.Parse("<a>test</a>");
I can create an XDocumentType using:
XDocumentType doctype = new XDocumentType("a", "-//TEST//", "test.dtd", "");
But how do I apply that to the existing XDocument?
You can add an XDocumentType to an existing XDocument, but it must be the first element added. The documentation surrounding this is vague.
Thanks to Jeroen for pointing out the convenient approach of using AddFirst in the comments. This approach allows you to write the following code, which shows how to add the XDocumentType after the XDocument already has elements:
var doc = XDocument.Parse("<a>test</a>");
var doctype = new XDocumentType("a", "-//TEST//", "test.dtd", "");
doc.AddFirst(doctype);
Alternately, you could use the Add method to add an XDocumentType to an existing XDocument, but the caveat is that no other element should exist since it has to be first.
XDocument xDocument = new XDocument();
XDocumentType documentType = new XDocumentType("Books", null, "Books.dtd", null);
xDocument.Add(documentType);
On the other hand, the following is invalid and would result in an InvalidOperationException: "This operation would create an incorrectly structured document."
xDocument.Add(new XElement("Books"));
xDocument.Add(documentType); // invalid, element added before doctype
Just pass it to the XDocument constructor (full example):
XDocument doc = new XDocument(
new XDocumentType("a", "-//TEST//", "test.dtd", ""),
new XElement("a", "test")
);
or use XDocument.Add (the XDocumentType has to be added before the root element):
XDocument doc = new XDocument();
doc.Add(new XDocumentType("a", "-//TEST//", "test.dtd", ""));
doc.Add(XElement.Parse("<a>test</a>"));