0

I have Customer XML with date-time fields but sometimes there are only dates. I need a result with only date-time fields and no date fields. (The xml I work with hat much more fields and is nested)

I thinks there is a better way then my brute force attempt.

xml = "<root><date>2003-07-15T10:00:00</date><enddate>2016-02-02</enddate><startdate>2000-02-10</startdate></root>";
string result = string.Empty;
if (!string.IsNullOrWhiteSpace(xml))
{
  XDocument doc = XDocument.Parse(xml);
  string xml1 = doc.ToString();
  Regex rgx = new Regex(@">(\d{4}-\d\d-\d\d)</");
  result = rgx.Replace(xml1, ">$1T00:00:00</");
}
4
  • how is the XML generated? Do you have any control over that? You mention XDocument and Linq-to-xml - is that how you're generating it? Commented Sep 28, 2015 at 15:14
  • Agreed. If possible, fixing the XML is the right way to resolve this, not writing code to account for an invalid document. Trying to fix inconsistent data generally leads to spaghetti code and headaches down the road (eg. when some other date format ends up in the XML because the owning developer is not following conventions). Commented Sep 28, 2015 at 15:21
  • Nothing need to be fixed and shouldn't be fixed. You need the time zone to prevent errors. Without the time zone you will get the wrong date. Simply read the dates and parse to a DateTime object which will convert the dates to the correct actual date. Commented Sep 28, 2015 at 17:00
  • I need to Parse old XML files and deliver them to another program. I don't have control of the file content and the other program. The other program expects date-time fields. I have to write a parser to glue them together... Commented Sep 29, 2015 at 6:19

1 Answer 1

1

Is this what you mean?

string xml = @"<root><date>2003-07-15T10:00:00</date>
<enddate>2016-02-02</enddate>
<startdate>2000-02-10</startdate>
</root>";

  XDocument doc = XDocument.Parse(xml);

  DateTime t;
  doc
    .DescendantNodes()
    .Where (d => d.NodeType == XmlNodeType.Text && 
      DateTime.TryParse(d.ToString(),out t))
    .ToList()
    .ForEach( n => n.Parent.SetValue(DateTime.Parse(n.ToString())));
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! I didn't think of DateTime.TryParse in this content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.